2
votes

I would like to add a placeholder to my date input to show visitors using firefox which format the date must have.
Using Zend Framework 2, I want to be able to generate an input equivalent to :

<input type="date" placeholder="yyyy-mm-dd">

inside my Form class.
Here is the Form class I have right now :

<?php
  namespace MyModule\Form;

  use Zend\Form\Form;

  class MyModuleForm extends Form {
      public function __construct($name = null) {
          parent::__construct('myModule');
          $this->add(array(
              'name' => 'TheDate',
              'type' => 'date',
              'attributes' => array(
                    'placeholder' => 'yyyy-mm-dd',
                    'class' => 'form-control',
               )
          ));
      }
  }
?>

But Zend seems to skip the "placeholder" attribute and generates only :

<input class="form-control" type="date" value="" name="TheDate">

In the worst case scenario, I know I can also definse the "value" attribute instead (though I would like not to, just in case the user doesn't pay attention and doesn't change it), or add the placeholder manually using javascript. But is there a more elegant way to do what I want to achieve through the Form class of Zend ?

3

3 Answers

1
votes

Edit : I found the answer I was looking for since the beginning thank to this post.

The solution is to go into the AbstractHelper.php present in the namespace Zend\Form\View\Helper.

There, there is a protected array of attributes that should be valid globally.

Adding

'placeholder'        => true,

to $validGlobalAttributes fixed everything and was what I was a good enough answer to me.
An even better way would be to change this variable by inheritance instead of modifying it into the framework, but I don't have enough time for it right now.

0
votes

You can't have placeholder on your date input due to the UI, which is triggered onfocus. Therefore you have to hack/fake it.

Change the 'type' => 'date', to 'type' => 'text',. You will see the placeholder now. This Javascript will help you triggering the date field on focus, and keep the placeholder.

$('.form-control').on('focus', function() {
  $(this).attr('type', 'date') }
).on('blur', function() {
  $(this).attr('type'), 'text') }
)
0
votes

I guess, Zend FormDate does not support placeholder. You can check this on repo. For example,

Every form element has a Helper in (Zend\Form\View\Helper) and some of them has validTagAttributes as a class element. You can check FormEmail view helper class for this.

But, FormDate dont have a validTagAttributes. So, your invalid attributes ignored in prepareAttributes() method.

I think, if you want to palceholder on your date form element, you can create a custom FormDate element view helper and use it.