【问题标题】:CakePHP 3 Modeless Form PersistenceCakePHP 3 无模式表单持久性
【发布时间】:2018-05-14 20:23:45
【问题描述】:

我正在根据here 给出的示例创建一个无模式表单。一旦用户单击提交按钮,我就会从数据库中检索一些信息并将其显示在表单下方的表格中。当我点击提交按钮时,表单每次都会显示startend 的默认值,这导致我的用户使用该页面时感到有些困惑。

有没有办法让FormHelper 显示最终用户提交的值而不是默认值?

src/Form/StartEndForm.php

namespace App\Form;

use Cake\Form\Form;

class StartEndForm extends Form{

    protected function _buildSchema(Schema $schema) {
        return $schema->addField('start', [
                'type' => 'date', 
                'default' => new Time('-1 month')
            ])
            ->addField('end', [
                'type' => 'date', 
                'default' => new Time()
            ]);
    }

    protected function _buildValidator(Validator $validator) {
        return $validator->add('start', 'date', [
                'rule' => ['date'], 
                'message' => 'Please provide a valid date'
            ])
            ->add('end', 'date', [
                'rule' => ['date'], 
                'message' => 'Please provide a valid date'
            ]);
    }

    protected function _execute(array $data) {
        //do some SQL stuff and return the value
    }
}

src/Template/Logs/index.ctp

echo $this->Form->create($form, [
    'class' => 'start-end-date', 
    'type' => 'get'
]);
echo $this->Form->input('start');
echo $this->Form->input('end');
echo $this->Form->submit('Submit');
echo $this->Form->end();

//If values were returned, create a table
foreach(....)....

【问题讨论】:

    标签: php cakephp cakephp-3.x


    【解决方案1】:

    您正在使用基于GET 的表单,即表单值是通过查询字符串发送的,默认情况下,表单助手在查找可能的数据以填充其控件时不会考​​虑查询字符串,因此您最终将使用架构默认值填充表单。

    您可以启用查询字符串查找(从 CakePHP 3.4 开始可用):

    echo $this->Form->create($article, [
        'class' => 'start-end-date', 
        'type' => 'get'
        'valueSources' => [
            'query', // < add this _before_ the default `context` source
            'context'
        ]
    ]);
    

    这将使表单助手显式查找当前请求中的查询数据,或者您可以切换到使用POST 表单,它将自动获取数据,因为POST 数据默认由所有内置表单上下文(ArrayEntityFormNull),可以作为后备,也可以作为主要来源。

    另见

    【讨论】:

    • 这成功了。非常感谢您的解释和食谱链接!
    猜你喜欢
    • 2011-05-02
    • 2012-10-07
    • 2017-12-29
    • 2018-06-13
    • 2013-08-24
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多