从视图中访问invalidFields

时间:2011-10-21 19:31:04

标签: cakephp cakephp-1.3

我有一个表单,可以从几个模型中收集信息,这些模型在关联中分开几层。出于这个原因,我必须单独保存每个,如果有任何失败,则报告回视图,以便显示错误消息。由于顺序保存,我认为,任何错误都没有正确显示,我也没有发现isFieldError()方法正在捕获错误的存在。

知道如何在视图级别访问此数据以检查错误吗?我想验证所有3个模型,以便我可以同时显示所有错误,同时避免创建手动数据结构并对其进行测试。是否有我可以访问的本机Cake功能/数据,因此这不是一个完全自定义的解决方案,我不能在更传统的实例中使用?

# Controller snippet
if( $this->Proposal->Requestor->saveField( 'phone_number', $this->data['Requestor']['phone_number'] ) && $this->Proposal->Requestor->Building->saveAll( $this->data ) ) {
  # Save off the proposal and message record.
  exit( 'saved' );
}      
else {
  $this->Session->setFlash( 'We can\'t send your quote just yet. Please correct the errors below.', null, null, 'error' );
  # At this point, I may have 2 or more models with validation errors to display
}

# Snippet from an element loaded into the view
# $model = Requestor, but the condition evaluates to false
<?php if( $this->Form->isFieldError( $model . '.phone_number' ) ): ?>
  <?php echo $this->Form->error( $model . '.phone_number' ) ?>
<?php endif; ?>

感谢。

1 个答案:

答案 0 :(得分:0)

这是开源软件的神奇之处。在源代码中进行了一些挖掘,向我展示了$this->Form->isFieldError最终从名为$validationErrors的视图变量中读取。在进行独立保存时,我只需在控制器操作中使用相同名称写入本地变量并手动设置。因此,非常规过程映射到传统结果,视图代码不需要识别任何类型的自定义结构。

# Compile our validation errors from each separate
$validationErrors = array();
if( !$this->Proposal->Requestor->validates( array( 'fieldList' => array_keys( $this->data['Requestor'] ) ) ) ) {
  $validationErrors['Requestor'] = $this->Proposal->Requestor->validationErrors;
}
if( !$this->Proposal->Requestor->Building->saveAll( $this->data ) ) {
  $validationErrors = Set::merge( $validationErrors, $this->Proposal->Requestor->Building->validationErrors );
}

if( empty( $validationErrors ) ) {
  # TODO: perform any post-save actions
}
else {
  # Write the complete list of validation errors to the view
  $this->set( compact( 'validationErrors' ) );
}

如果有更好的方法,请有人告诉我。至少目前,这似乎正在做正确的事情。

相关问题