[英]Dynamically add form fields
我在CakePHP應用程序中動態添加表單字段時遇到問題,我不知道如何解決。 我想在EventsController / add.ctp中添加要添加的事件的表單,我想在其中包含事件.name,Dates.from,Dates.to,Dates.endregister,Dates.location_id,{可選的其他Dates.from,Dates.to ,...},Terms_mem.teacher_id {和其他可選的Terms_mem.teacher_id}我的表格是:
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(150) NOT NULL
);
CREATE TABLE `dates` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`from` datetime NOT NULL,
`to` datetime NOT NULL,
`endregister` datetime,
`event_id` int(11) NOT NULL,
`location_id` int(11) NOT NULL,
FOREIGN KEY (`event_id`) REFERENCES `events`(`id`),
FOREIGN KEY (`location_id`) REFERENCES `locations`(`id`)
);
CREATE TABLE `locations` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`street` varchar(70),
`city` varchar(70) NOT NULL
);
CREATE TABLE `dates_mem` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`teacher_id` int(11) NOT NULL,
`date_id` int(11) NOT NULL,
FOREIGN KEY (`teacher_id`) REFERENCES `users`(`id`),
FOREIGN KEY (`date_id`) REFERENCES `dates`(`id`)
)
所以形式看起來像:
<?php echo $this->Form->create('Event'); ?>
<fieldset>
<?php
// events
echo $this->Form->input('name');
// dates
echo $this->Form->input('from');
echo $this->Form->input('to');
echo $this->Form->input('endregister');
echo $this->Form->input('location_id');
/* HERE optional dynamically add next inputs for dates (from, to, ...) */
// teachers
echo $this->Form->input('teacher_id');
/* HERE optional dynamically add next inputs for teachers(teacher_id) */
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
並將所有字段保存到相應的表中。 在CakePHP 2.4版中可能嗎? 如果是,您能幫我嗎?
編輯:
burzum寫道:
$this->Form->input('Date.0.from');
$this->Form->input('Date.0.to');
$this->Form->input('Date.1.from');
$this->Form->input('Date.1.to');
是否可以這樣做: 因此,單擊按鈕后,將字段Date.1.from和Date.1.to動態添加到表單中,以添加下一個日期
$this->Form->input('Date.0.from');
$this->Form->input('Date.0.to');
// button add next date
$this->Form->input('Date.1.from'); // after click on add next date
$this->Form->input('Date.1.to'); // after click on add next date
// button add next date
$this->Form->input('Date.2.from'); // after click on add next date
$this->Form->input('Date.2.to'); // after click on add next date
// button add next date
您是否嘗試過閱讀手冊? 如果不閱讀該手冊,則在“ 保存數據 ”部分中進行了詳細說明。 見這部分 。
簡而言之,首先是視圖
$this->Form->input('FirstModel.field1');
$this->Form->input('SecondModel.field1');
$this->Form->input('SecondModel.field2');
$this->Form->input('Date.0.from');
$this->Form->input('Date.0.to');
$this->Form->input('Date.1.from');
$this->Form->input('Date.1.to');
// ...
控制器:
$this->saveAll($this->request->data);
是的,您可以動態添加字段,使用Javascript將其他字段注入DOM。 通過JS模板或AJAX。 只要確保您生成的表單輸入遵循CakePHP約定,並且將JS生成的字段列入白名單即可。 另外,請確保您非常嚴格地驗證了白名單中的輸入,以避免不必要的內容添加。 如果尚未使用安全組件,則應使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.