Search code examples
cakephpformhelper

CakePHP trouble using FormHelper for a year menu


Cake 2.2.4

I have a database sport_year field set to the YEAR data type. I've tried two approaches to creating a year menu for my add/edit views, but both have their own problems.

Using $this->Form->input:

echo $this->Form->input('sport_year', array(
    'type' => 'date',
    'dateFormat' => 'Y',
    'name' => 'data[Sport][sport_year]',
    'minYear' => date('Y') - 2,
    'maxYear' => date('Y') + 1,
    'label' => 'Year',
    'empty' => '- select -'
));

The code works fine to add or edit data (as does the validation), but when arriving at the edit page existing year data is not properly selected in the form. The data array does show [sport_year] => 2012, but 2012 is not selected in the menu.

echo $this->Form->year(
    'sport_year', 
    date('Y') - 2, 
    date('Y') + 1, 
    array(
        'name' => 'data[Sport][sport_year]', 
        'label' => 'Year', 
        'empty' => '- select -'
    )
);

The year helper seems to correctly retrieve and select the existing data, but the label does not work, and it doesn't correctly render the field as required even though my Model has validation set. It does still require the data, but it ignores my Model custom message and is falling back to a save error message in my controller.


Solution

  • $this->Form->year() will never show a label. Only $this->Form->input() adds labels as it is a wrapper method and year() is for creating a year field.

    The code in cake is something like:

    public function input() {
        echo '<div>';
        echo $this->label(...);
        echo $this->year(...);
        echo '</div>';
    }
    

    Taking this code, you do not need name as cake will be generating that already. If you are not in the Sport model you can use input('Sport.sport_year', ...)

    If you read the docs you should see there is a default option for inputs. you can use that or make sure that $this->request->data['Sport']['sport_year'] is set to the year you want.

    You could also set the value option.

    echo $this->Form->input('sport_year', array(
        'type' => 'date',
        'dateFormat' => 'Y',
        'minYear' => date('Y') - 2,
        'maxYear' => date('Y') + 1,
        'label' => 'Year',
        'empty' => '- select -',
        'default' => date('Y')
    ));
    

    or

    echo $this->Form->input('sport_year', array(
        'type' => 'date',
        'dateFormat' => 'Y',
        'minYear' => date('Y') - 2,
        'maxYear' => date('Y') + 1,
        'label' => 'Year',
        'empty' => '- select -',
        'value' => date('Y')
    ));