【问题标题】:kohana - how to get _external error messages from a filekohana - 如何从文件中获取 _external 错误消息
【发布时间】:2014-05-04 04:19:10
【问题描述】:

我正在使用 Kohana 的验证方法来确定表单中是否存在某些强制值。在验证确认密码时,ORM_Validation_Exception 的“错误”方法返回以下格式的数组

array(1) (
    "_external" => array(1) (
        "password_confirm" => string(45) "password confirm must be the same as password"
    )
)

我怎样才能使它遵循与其余错误相同的约定,以便我可以执行以下操作并仅遍历视图文件中的错误。

 $Errors = $e->errors('user'); // inside the controller

<?php if ($Errors): ?>
<p class="message">Some errors were encountered, please check the details you entered.</p>
<ul class="errors">
<?php 
echo Debug::vars($Errors);
foreach ($Errors as $message): ?>
    <li><?php echo $message ?></li>
<?php endforeach ?>
<?php endif; 

我尝试在messages(也尝试将它放在/messages/model)文件夹下添加一个_external 文件,但它似乎不起作用。我应该调用$Errors = $e-&gt;errors('_external') 来加载错误消息吗?在这种情况下,我如何从包含其余错误消息的“用户”文件中加载消息?

【问题讨论】:

    标签: php kohana


    【解决方案1】:

    即使您使用消息文件(在您的情况下应该进入messages/user/&lt;model&gt;/_external.php)翻译错误,您的$Errors 数组仍将具有相同的结构,即外部错误消息将位于它们自己的子数组中, $Errors['_external'].

    如果您需要将其“展平”,我认为您必须手动执行此操作,例如:

    // The next line is from your question
    $Errors = $e->errors('user'); // inside the controller
    
    // If there are any '_external' errors, we place them directly into $Errors
    if (isset($Errors['_external']))
    {
        // Keeps track of a possible edge case in which the _external
        // array has a key '_external'
        $double_external = isset($Errors['_external']['_external']);
    
        // Move the elements of the sub-array of external errors into the main array
        $Errors = array_merge_recursive($Errors, $Errors['_external']);
    
        // Remove the '_external' subarray, except in the edge case
        if (!$double_external)
        {
            unset($Errors['_external']);
        }
    }            
    

    【讨论】:

      【解决方案2】:

      您应该合并它们,据我所知,框架中没有任何功能或任何东西可以为您执行此操作。很遗憾。

      $errors = $e->errors('user');
      $errors = Arr::merge($errors, Arr::get($errors, '_external'));
      unset($errors['_external']);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-28
        • 2023-03-08
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多