Search code examples
phpcakephpformhelper

cakePHP: How to change the ID of a form element (using the form helper)?


I've created a form which has a loop to display a number of rows. I have a select on each row using the form helper. The IDs it creates are all the same, is there a way to add a counter, or some defining info to the ID?

I'm using $this->Form->input('city_id') to output a select of the cities from my city model. All the IDs are ModelCityId. I'd like to get something like ModelCityId1, ModelCityId2, ModelCityId3, etc. Is this possible? Or is there a better way to go about displaying options in a loop?

Thanks for any suggestions you might have.

Here is the relevant part of the code.

while ($current_date != $departure_date) {
  $current_date = date("d-M-y", strtotime($current_date . " +1 day"));
  $output .= '<tr>';
  $output .= '<td>'.$current_date.'</td>';
  // irrelevant other columns
  $output .= '<td>'.$this->Form->input('city_id', array('label' => '', 'empty' => true)).'</td>';
  $output .= '</tr>';
}

Solution

  • If the ids are the same, the name is the same as well. That'll mess up your data when you submit it. You're looking for this syntax:

    $this->Form->input("ModelName.$i.city_id", array(...))
    

    Use the ModelName that you're making the form for (i.e. the same as in $this->Form->create('ModelName')).