Jelle Keizer
Jelle Keizer

Reputation: 721

Form input produces double key names for field name in cakephp

Why does this code produce a form input field with the double array key names as shown below in html output

 echo $this->Form->input(
                                    'year', array(
                                'div' => false,
                                'id' => 'year',
                                'label' => false,
                                'type' => 'date',
                                'dateFormat' => 'Y',
                                'minYear' => date('Y') - 30,
                                'maxYear' => date('Y') + 1,
                                'selected' => date('Y-m-d', strtotime('+1 month')),
                                    )
                            );

html output from code above

 <label class="select">
  Year     <select name="data[InvoiceRun][year][year]" id="yearYear">
<option value="2015" selected="selected">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
..........
</select>  
</label>

Upvotes: 0

Views: 273

Answers (1)

Kai
Kai

Reputation: 3823

This is because you have selected the input type as "date." "Date" normally makes day, month, year selects, so even though you have it formatted to only have year input, it's still behaving as if there would be other inputs.

If you look on the Cookbook, at http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#field-naming-conventions

FormHelper uses several field-suffixes internally for datetime input creation. If you are using fields named year, month, day, hour, minute, or meridian and having issues getting the correct input, you can set the name attribute to override the default behavior:

echo $this->Form->input('Model.year', array(
    'type' => 'text',
    'name' => 'data[Model][year]'
));

So in other words, the following should work:

echo $this->Form->input(
    'year', array(
          'name' => 'data[InvoiceRun][year]', //new setting
          'div' => false,
          'id' => 'year',
          'label' => false,
          'type' => 'date',
          'dateFormat' => 'Y',
          'minYear' => date('Y') - 30,
          'maxYear' => date('Y') + 1,
          'selected' => date('Y-m-d', strtotime('+1 month')),
      )
);

If it does not, then the other option is to create the input as type "select" instead, and recreate the year options based on the current year.

Upvotes: 1

Related Questions