参考にさせて頂いたページ
U2Kの覚え書き CakePHP2.0で、FormHelperをカスタマイズする方法
app/View/Helper/MyFormHelper.phpの作成とその記述内容
例として、$this->Form->text()のとき出力されるHTMLを拡張する場合は以下のような感じ。
<?php // FormHelperの使用を宣言 App::uses('FormHelper', 'View/Helper'); // FormHelperを継承して、MyFormHelperクラスを作成 class MyFormHelper extends FormHelper { // public function __construct(View $View, $settings = array()) { parent::__construct($View, $settings); } /** * textメソッドを拡張 */ public function text($fieldName, $options = array()) { $output = '<div class="hoge">'; $output .= parent::text($fieldName, $options); $output .= '</div>'; return $output; } }
app/Controller/AppController.php
例として、AppController.php内のAppControllerクラス内で、$helpersを設定する部分を抜粋すると以下のような感じ。
public $helpers = array( 'Form' => array( 'className' => 'MyForm' ) );
Controllerにこのように記述しておくことで、Viewで$this->Form->text
や$this->Form->input
などを記述したときには、MyFormHelperクラスが使用されるようになる。
任意のctpファイルに記述する内容
例として以下のような感じ。
<?php echo $this->Form->text('hoge'); ?>
もっと拡張する
MyFormHelperクラスのtextメソッドの引数について、$optionsのデフォルト値を設定しておくと、Viewのソースコードがすっきりしそう。
type="text"の要素以外にもcheckboxなども拡張すると良さそう。