CakePHP - 如何修改FormHelper并在输入后添加div?

时间:2013-01-30 09:49:57

标签: cakephp

我正在尝试修改FormHelper的行为以满足我的应用程序要求。我想使用原生FormHelper但是对于所有输入我需要添加一些短消息,为用户提供帮助并描述特定字段。

我的想法是创建自己的帮助器并传递帮助消息作为参数。此函数将修改表单的inputDefaults设置并调用本机FormHelper输入函数。

例如:

class MsgFormHelper extends AppHelper {
      public function input($name, $message, $options) {
        $this->_View->Form->_inputDefaults['after'] .= '<div>'.$message.'</div>';
        return $this->_View->Form->input($name, $options);
    }
}

但是这个解决方案注意到了这个错误:

  

注意(8):间接修改重载属性   FormHelper :: $ _ inputDefaults没有效果......

有没有办法在form的inputDefaults设置中修改“after”值?

2 个答案:

答案 0 :(得分:0)

我可能找到了一个解决方案(它有效,但我不确定它是否违反了CakePHP的一些原则)。感谢您的意见。

class MsgFormHelper extends AppHelper {

    public function __construct(View $view, $settings = array()) {
        parent::__construct($view, $settings);
    }

    public function input($name, $message, $options) {

        $add_message = true;

        if (isset($options['after'])) {
            $options['after'] = trim($options['after']);
            $add_message = empty($options['after']);
        }

        if ($add_message) {
            $options['after'] = '<div class="input-help">' . $message . '</div>' . $this->_View->Form->_inputDefaults['after'];
        }

        return $this->_View->Form->input($name, $options);
    }

}

答案 1 :(得分:0)

您应该将FormHelper本身扩展为AppHelper。然后在你的控制器中使用别名功能,这样你仍然可以在视图中使用$this->Form->input(),但它实际上会引用你的自定义助手。

public $helpers = array('Form' => array('className' => 'MsgForm'))