首页 > 解决方案 > cakephp 3中具有相同控制器的同一ctp文件中的多个表单

问题描述

我在一个 ctp 文件中有 2 种不同形式的问题。
解释:我想在同一个控制器中使用与不同动作相关的两种形式。我使用第一个表单在表格中添加 2 个文本字段,我使用第二个表单来搜索和检索数据。

我的ctp:

表格 1 添加消息和电子邮件

<?= $this->Form->create($message) ?>
<div class="form-group">
    <label for="name" class="col-form-label">Name</label>
    <input name="name" class="form-control" id="name" placeholder="Your Name" type="text">
</div>
<div class="form-group">
    <label for="email" class="col-form-label">Email</label>
    <input name="email" class="form-control" id="email" placeholder="Your Email" type="email">
</div>
<?= $this->Form->button('Submit', ['class'=> "btn btn-primary large icon float-right"]); 
$this->Form->end() ?>   

表格 2 搜索字段:

<?= $this->Form->create(null, ['url' => ['action' => 'search']]) ?>
<div class="form-group">
    <label for="what" class="col-form-label">What?</label>
    <input name="what" class="form-control" id="what" placeholder="What are you looking for?" type="text">
</div>
<div class="form-group">
    <?php echo $this->Form->input('country_id', [
        'options' => $countries,
        'id' => 'country_id',
        'label' => ['text' => __('Where?')]
    ]); ?>
</div>
<button type="submit" class="btn btn-primary width-100">Search</button>
<?= $this->Form->end() ?>

所以我点击提交它工作正常但是当我点击搜索时它没有转到所需的操作它仍然在同一个操作中。谢谢!

标签: formscakephpcakephp-3.x

解决方案


这段代码没有做你认为它正在做的事情:

<?= $this->Form->button('Submit', ['class'=> "btn btn-primary large icon float-right"]); 
$this->Form->end() ?>

它会回显提交按钮,但不会回显表单结束标记。然后您打开另一个表单,但浏览器可能会将其解释为错误标记并忽略它。(从技术上讲,我认为浏览器对这种格式错误的 HTML 的行为是未定义的,因此您可能会从不同的浏览器获得不同的行为。)

试试这个:

<?php
echo $this->Form->button('Submit', ['class'=> "btn btn-primary large icon float-right"]); 
echo $this->Form->end();
?>

或者

<?= $this->Form->button('Submit', ['class'=> "btn btn-primary large icon float-right"]); 
echo $this->Form->end() ?>

或者

<?= $this->Form->button('Submit', ['class'=> "btn btn-primary large icon float-right"]) .
$this->Form->end() ?>

我推荐第一个选项,因为它的代码更清晰,并且在未来的编辑中不太容易意外损坏;在我正在管理的项目中,我永远不会允许后两者中的任何一个。


推荐阅读