Answers.Body: <p>Here’s what your field type’s <a href="http://buildwithcraft.com/classreference/fieldtypes/IFieldType#getInputHtml-detail" rel="nofollow">getInputHtml()</a> method should look like:</p>
  
  <pre class="lang-php prettyprint-override"><code>public function getInputHtml($name, $value)
  {
      // If $value['trial_end'] is set, make sure that it's a DateTime object
      if (!empty($value['trial_end']))
      {
          $value['trial_end'] = DateTime::createFromString($value['trial_end']);
      }
      else
      {
          $value['trial_end'] = '';
      }
  
      return craft()-&gt;templates-&gt;render('myplugin/input', array(
          'id'    =&gt; craft()-&gt;templates-&gt;formatInputId($name),
          'name'  =&gt; $name,
          'value' =&gt; $value,
      ));
  }
  </code></pre>
  
  <p>Then your plugin’s input.html template would be responsible for showing the Datepicker input.</p>
  
  <p>The easiest way to create a Datepicker input is to either include the <a href="https://github.com/pixelandtonic/Craft-Release/blob/master/app/templates/_includes/forms/date.html" rel="nofollow">_includes/forms/date.html</a> template directly into your template, or use the <a href="https://github.com/pixelandtonic/Craft-Release/blob/master/app/templates/_includes/forms.html#L24" rel="nofollow">date()</a> macro from _includes/forms.html. </p>
  
  <pre class="lang-twig prettyprint-override"><code>{% from "_includes/forms" import date %}
  
  {{ date({
      id: id ~ '-trial_end',
      name: name ~ '[trial_end]',
      value: value.trial_end
  }) }}
  </code></pre>
  
  <p>However if you need to tweak the HTML, such as adding that <code>ata-stripe="trial_end"</code> attribute, you can just copy the HTML from the _includes/forms/date.html template directly into yours.</p>
  
  <p>In your case, it’s probably not working because you have that <code>hasDatepicker</code> class on your <code>&lt;input&gt;</code>, which tells the Datepicker JS that a datepicker instance has already been assigned to that input, so the new datepicker initialization is getting skipped. Remove that class and you should be good to go.</p>
  
  <p>When an entry is saved, you will need to convert the user-submitted date value into a DateTime object, which you can do using <a href="http://buildwithcraft.com/classreference/etc/dates/DateTime#createFromString-detail" rel="nofollow">DateTime::createFromString()</a>.</p>
  
  <p>On a normal field type you would want to put that code within <a href="http://buildwithcraft.com/classreference/fieldtypes/IFieldType#prepValueFromPost-detail" rel="nofollow">prepValueFromPost()</a>, like this:</p>
  
  <pre class="lang-php prettyprint-override"><code>public function prepValueFromPost($value)
  {
      // Convert trial_end to a DateTime object
      $value['trial_end'] = DateTime::createFromString($value['trial_end']);
  
      return $value;
  }
  </code></pre>
  
  <p>However in your case, if your field type isn’t storing any data and its <a href="http://buildwithcraft.com/classreference/fieldtypes/IFieldType#defineContentAttribute-detail" rel="nofollow">defineAttributeConfig()</a> method is returning <code>false</code>, a better place to put it would be in <a href="http://buildwithcraft.com/classreference/fieldtypes/IFieldType#onAfterElementSave-detail" rel="nofollow">onAfterElementSave()</a>:</p>
  
  <pre class="lang-php prettyprint-override"><code>public function onAfterElementSave()
  {
      // Get the raw POST value for this field
      $value = $this-&gt;element-&gt;getContent()-&gt;getAttribute($this-&gt;model-&gt;handle);
  
      // Convert trial_end to a DateTime object
      $value['trial_end'] = DateTime::createFromString($value['trial_end']);
  
      // ...
  }
  </code></pre>
  
  <p>If you’re looking for an example third party field type that works with dates, check out our <a href="https://github.com/pixelandtonic/StoreHours" rel="nofollow">Store Hours</a> plugin. It’s using timepickers rather than datepickers, but those both work exactly the same.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:10:45.270Z
Answers.Text: Thanks Brandon! I wish it were that simple. Unfortunately, I am not actually creating a real date field that is stored in the database but rather an input field, that just borrows the UI of a craft date field. I updated my question to clarify.
Answers.UserDisplayName: Douglas McDonald
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:21:19.790Z
Answers.Text: @DouglasMcDonald That’s fine - the majority of the answer still applies. Just added a little more detail to the end for your use case.
Answers.UserDisplayName: Brandon Kelly
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:44:47.003Z
Answers.Text: I tried using the date() macro and it works perfectly. However, it doesn't allow me to add a custom attribute `data-stripe="trialEnd"`. What I don't understand is that I am replicating the functionality of the '_includes/forms/date.html' inline, but the datepicker does not seem to work. There is some small piece missing to the puzzle somewhere. Is the date field instantiated in some way before the template gets rendered?
Answers.UserDisplayName: Douglas McDonald
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:53:30.037Z
Answers.Text: Looking at the actual source output, the two fields (custom vs using date() macro) next to each other look identical (minus the extra attribute). And the javascript `var $datePicker=...` includes at the bottom are identical.
Answers.UserDisplayName: Douglas McDonald
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:55:11.790Z
Answers.Text: @DouglasMcDonald Ah I missed that `data-stripe="trial_end"` attribute. That’s a good case for us tweaking the macro to allow custom attributes. Just updated the answer again, this time showing what’s wrong with your HTML.
Answers.UserDisplayName: Brandon Kelly
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T18:59:05.017Z
Answers.Text: Perfect! You're a genius! Problem solved. Thank you. Check out the cool stuff we can do with Craft ;)
Answers.UserDisplayName: Douglas McDonald
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-10-22T17:42:36.913Z
Answers.LastActivityDate: 2014-10-22T18:54:48.783Z
Answers.LastEditDate: 2014-10-22T18:54:48.783Z
Answers.UserDisplayName: Brandon Kelly
Body: <p>I would like to impliment the native craft datepicker ui in my custom fieldType. From looking at the native <code>date</code> template (<code>craft/app/templates/_includes/form/date.html</code>) I can see that it inserts javascript using <code>includeJs</code>, which I have followed exactly. Here is my template code:</p>
  
  <pre><code>&lt;div class="input"&gt;
      &lt;div class="datewrapper"&gt;
          &lt;input type="text" autocomplete="off" value="" size="10" id="trial_end" data-stripe="trial_end" class="text hasDatepicker"&gt;
       &lt;/div&gt;
  &lt;/div&gt;
  
  {%- set js %}
      var $datePicker = $('#{{ 'trial_end'|namespaceInputId|e('js') }}');
      $datePicker.datepicker({
          constrainInput: false,
          dateFormat: '{{ craft.i18n.datepickerJsFormat }}',
          defaultDate: new Date(),
          prevText:   '{{ "Prev"|t|e('js') }}',
          nextText:   '{{ "Next"|t|e('js') }}',
      });
  {%- endset %}
  {%- includeJs js %}
  </code></pre>
  
  <p>I have confirmed that the js output is identical to the other native date fields, and that the namespaced <code>id</code> matches between the js selector and the html input field id. But no datepicker. Is there a piece missing?</p>
  
  <p>Update: Perhaps my question needs some clarification. My field type includes additional 'dummy' fields that will never get stored in the database, but rather are only used to collect information from the user that will be sent via ajax to a 3rd party service, with the result <code>customerId</code> being stored in the database. One of those dummy fields is a date field that I would like to use the native datepicker for. Here is an image:</p>
  
  <p><img src="https://i.sstatic.net/ZoR9P.png" alt="This is the custom field"></p>
  
  <p>Yes. That is all one field! that only stores a <code>customerid</code> from a third party service (Stripe), and loads all of the customer account info via ajax. The actual field 'customerID' is never exposed to the client, as it generated automatically.</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2014-10-17T00:16:35.727Z
Comments.Text: I have also tried to delay the instantiation of the datepicker using `.setTimeout()`, instantiate on demand using `$body.on('click', $elmt, function(e){...});`, and force it on with `$datepicker.show();`. But no luck — at a total loss.
Comments.UserDisplayName: Douglas McDonald
Tags: <plugin-development><custom-fieldtype>
Title: How to use the native datepicker ui in custom fieldTypes?
ThreadText: # How to use the native datepicker ui in custom fieldTypes?
  
  (Asked by: username_0 on 2014-10-14)
  
  I would like to impliment the native craft datepicker ui in my custom fieldType. From looking at the native `date` template (`craft/app/templates/_includes/form/date.html`) I can see that it inserts javascript using `includeJs`, which I have followed exactly. Here is my template code:
  
  ```
  <div class="input">
      <div class="datewrapper">
          <input type="text" autocomplete="off" value="" size="10" id="trial_end" data-stripe="trial_end" class="text hasDatepicker">
       </div>
  </div>
  
  {%- set js %}
      var $datePicker = $('#{{ 'trial_end'|namespaceInputId|e('js') }}');
      $datePicker.datepicker({
          constrainInput: false,
          dateFormat: '{{ craft.i18n.datepickerJsFormat }}',
          defaultDate: new Date(),
          prevText:   '{{ "Prev"|t|e('js') }}',
          nextText:   '{{ "Next"|t|e('js') }}',
      });
  {%- endset %}
  {%- includeJs js %}
  
  ```
  
  I have confirmed that the js output is identical to the other native date fields, and that the namespaced `id` matches between the js selector and the html input field id. But no datepicker. Is there a piece missing?
  
  Update: Perhaps my question needs some clarification. My field type includes additional 'dummy' fields that will never get stored in the database, but rather are only used to collect information from the user that will be sent via ajax to a 3rd party service, with the result `customerId` being stored in the database. One of those dummy fields is a date field that I would like to use the native datepicker for. Here is an image:
  
  ![This is the custom field](https://i.sstatic.net/ZoR9P.png)
  
  Yes. That is all one field! that only stores a `customerid` from a third party service (Stripe), and loads all of the customer account info via ajax. The actual field 'customerID' is never exposed to the client, as it generated automatically.
  
  **Tags:** plugin-development, custom-fieldtype
  
  > **Comments:**
  > **username_0**: I have also tried to delay the instantiation of the datepicker using `.setTimeout()`, instantiate on demand using `$body.on('click', $elmt, function(e){...});`, and force it on with `$datepicker.show();`. But no luck — at a total loss.  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2014-10-22. Score: 5 | Accepted answer
  
  Here’s what your field type’s [getInputHtml()](http://buildwithcraft.com/classreference/fieldtypes/IFieldType#getInputHtml-detail) method should look like:
  
  ```php
  public function getInputHtml($name, $value)
  {
      // If $value['trial_end'] is set, make sure that it's a DateTime object
      if (!empty($value['trial_end']))
      {
          $value['trial_end'] = DateTime::createFromString($value['trial_end']);
      }
      else
      {
          $value['trial_end'] = '';
      }
  
      return craft()->templates->render('myplugin/input', array(
          'id'    => craft()->templates->formatInputId($name),
          'name'  => $name,
          'value' => $value,
      ));
  }
  
  ```
  
  Then your plugin’s input.html template would be responsible for showing the Datepicker input.
  
  The easiest way to create a Datepicker input is to either include the [\_includes/forms/date.html](https://github.com/pixelandtonic/Craft-Release/blob/master/app/templates/_includes/forms/date.html) template directly into your template, or use the [date()](https://github.com/pixelandtonic/Craft-Release/blob/master/app/templates/_includes/forms.html#L24) macro from \_includes/forms.html.
  
  ```twig
  {% from "_includes/forms" import date %}
  
  {{ date({
      id: id ~ '-trial_end',
      name: name ~ '[trial_end]',
      value: value.trial_end
  }) }}
  
  ```
  
  However if you need to tweak the HTML, such as adding that `ata-stripe="trial_end"` attribute, you can just copy the HTML from the \_includes/forms/date.html template directly into yours.
  
  In your case, it’s probably not working because you have that `hasDatepicker` class on your `<input>`, which tells the Datepicker JS that a datepicker instance has already been assigned to that input, so the new datepicker initialization is getting skipped. Remove that class and you should be good to go.
  
  When an entry is saved, you will need to convert the user-submitted date value into a DateTime object, which you can do using [DateTime::createFromString()](http://buildwithcraft.com/classreference/etc/dates/DateTime#createFromString-detail).
  
  On a normal field type you would want to put that code within [prepValueFromPost()](http://buildwithcraft.com/classreference/fieldtypes/IFieldType#prepValueFromPost-detail), like this:
  
  ```php
  public function prepValueFromPost($value)
  {
      // Convert trial_end to a DateTime object
      $value['trial_end'] = DateTime::createFromString($value['trial_end']);
  
      return $value;
  }
  
  ```
  
  However in your case, if your field type isn’t storing any data and its [defineAttributeConfig()](http://buildwithcraft.com/classreference/fieldtypes/IFieldType#defineContentAttribute-detail) method is returning `false`, a better place to put it would be in [onAfterElementSave()](http://buildwithcraft.com/classreference/fieldtypes/IFieldType#onAfterElementSave-detail):
  
  ```php
  public function onAfterElementSave()
  {
      // Get the raw POST value for this field
      $value = $this->element->getContent()->getAttribute($this->model->handle);
  
      // Convert trial_end to a DateTime object
      $value['trial_end'] = DateTime::createFromString($value['trial_end']);
  
      // ...
  }
  
  ```
  
  If you’re looking for an example third party field type that works with dates, check out our [Store Hours](https://github.com/pixelandtonic/StoreHours) plugin. It’s using timepickers rather than datepickers, but those both work exactly the same.
  
  > **Comments:**
  > **username_0**: Thanks username_1! I wish it were that simple. Unfortunately, I am not actually creating a real date field that is stored in the database but rather an input field, that just borrows the UI of a craft date field. I updated my question to clarify.  
  > **username_1**: @username_0 That’s fine - the majority of the answer still applies. Just added a little more detail to the end for your use case.  
  > **username_0**: I tried using the date() macro and it works perfectly. However, it doesn't allow me to add a custom attribute `data-stripe="trialEnd"`. What I don't understand is that I am replicating the functionality of the '_includes/forms/date.html' inline, but the datepicker does not seem to work. There is some small piece missing to the puzzle somewhere. Is the date field instantiated in some way before the template gets rendered?  
  > **username_0**: Looking at the actual source output, the two fields (custom vs using date() macro) next to each other look identical (minus the extra attribute). And the javascript `var $datePicker=...` includes at the bottom are identical.  
  > **username_1**: @username_0 Ah I missed that `data-stripe="trial_end"` attribute. That’s a good case for us tweaking the macro to allow custom attributes. Just updated the answer again, this time showing what’s wrong with your HTML.  
  > **username_0**: Perfect! You're a genius! Problem solved. Thank you. Check out the cool stuff we can do with Craft ;)  
  
  ---
  
  