开发者

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

开发者 https://www.devze.com 2023-02-14 11:33 出处:网络
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 defi

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.


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')).


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++;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号