繁体   English   中英

动态添加表单字段

[英]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.

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