简体   繁体   中英

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>';
}

As itchy points out, simply use a counter in your while loop to get a unique number.

Then all you have to do is assign it to your ID field

$this->Form->input('city_id', array('id' => 'somvalue' . $i));

Assuming $i is defined in your loop.

Edit: why can't you do something like this:

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

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 (ie the same as in $this->Form->create('ModelName') ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM