【问题标题】:Cannot initialize variable using beforeValidate无法使用 beforeValidate 初始化变量
【发布时间】:2014-08-28 19:01:11
【问题描述】:

我有一个在 AppModel.php 中指定的自定义行为,它会根据所选语言自动创建一个字段。因此,根据选择的语言,name_eng -> namename_fra -> name

...
$virtualField = sprintf($model->name.'.'.$name.'_%s', Configure::read('Config.language'));
$virtualFields[$name] = $virtualField;
$model->virtualFields = $virtualFields;
...

这部分有效。

当我提交编辑表单时出现问题,出现验证错误,并且当编辑视图显示错误提示时该字段不可用。我认为这是由于我的行为没有在此过程中被调用,或者$this->request->data 是使用表单数据创建的?

我想我会使用beforeValidate 来初始化这些值。但是,它没有解决:一旦我提交了给我这个错误的表单,该字段仍然不存在:

AppModel.php:

function beforeValidate(array $options = array()){
    //hard coded for test purposes
    $this->data['CertificateType']['name'] = $this->data['CertificateType']['name_'.Configure::read('Config.language')]
    return true;
}

在视图中(edit.ctp):

echo $this->request->data['CertificateType']['name'];

基本上,如何在提交表单但未验证后复制自定义行为的功能并初始化我的字段?

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    最终将所需的逻辑放在 AppController.php 中。现在一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多