HOME>WEBプログラム覚書>[CakePHP2]FormHelper をちょっとだけ便利に。

[CakePHP2]FormHelper をちょっとだけ便利に。

[CakePHP2.X] HtmlHelper、FormHelper、Viewは直接使わないほうがイイ。という記事を書いたので、 FormHelperを直接使わない場合、どのようなことができるのか書いておきます。地味なことしかやってないんで地味な例ですけど・・・

入力例や注意事項などを出力したい

フォームには入力例や、注意事項など書くことが多々あるかとおもいます。

一応、$options に before や after があるので前後に挿入することは可能ですが、他のはうざいほど余計なタグでラップするくせに、ここはタグでラップしてくれず入力したものがそのまま出力されます。 なのでタグを入れたい場合、直接HTMLタグを入力してもよいですが、 デザイン変更時やCSSライブラリやJavascript ライブラリとクラス名がかぶったりした場合、 全て修正しないとだめなので面倒です。

例えば、

HTML

  1. <div class="input email">
  2.     <label for="UserEmail">メールアドレス</label>
  3.     <input name="data[User][email]" type="email" id="UserEmail" />
  4.     <p class="example">入力例) jousou@example.com</p>
  5.     <ul class="help-list">
  6.         <li>20文字以内で入力してください。</li>
  7.         <li>半角英数字で入力してください。</li>
  8.     </ul>
  9. </div>
  10.  

のようなHTMLを出力したい場合、

View/User/form.php

  1. <?php
  2. echo $this->Form->input('User.email', array(
  3.     'label'    => 'メールアドレス',
  4.     'after' => '
  5.        <p class="example">入力例) jousou@example.com</p>
  6.        <ul class="help-list">
  7.            <li>20文字以内で入力してください。</li>
  8.            <li>半角英数字で入力してください。</li>
  9.        </ul>
  10.    ',
  11. ));
  12. ?>

と記述しなくてはなりません。PHPにタグを埋め込むとか苦痛ですよね。 なので、これをもっと簡単にかけて、変更も容易になるようなメソッドを追加します。

準備

FormHelperを継承したAppFormHelperを利用することにします。

AppController.php

  1. <?php
  2. AppController extends Controller
  3. {
  4.     public var $helper = array(
  5.         'Form' => array('className' => 'AppFormHelper')
  6.     );
  7. }
  8. ?>

こんな感じでFormHelperを自作のフォームヘルパーに変更します。

AppFormHelper

$optionsに help、helpText、helpList、example というキーがあった場合、それぞれ処理をおこなうようになっています。

View/Helper/AppFormHelper.php

  1. <?php
  2. App::uses('FormHelper', 'View/Helper');
  3.  
  4. class AppFormHelper extends FormHelper
  5. {
  6.     /**
  7.      * ここに記述したキーが $options にあった場合、
  8.      * コールバックを実行
  9.      *
  10.      * @var array
  11.      */
  12.     public $app_tags = array(
  13.         'help', 'helpText', 'helpList', 'example'
  14.     );
  15.  
  16.     /**
  17.      * $options に self::$app_tags で定義されたキーがあった場合、
  18.      * self::$key()を実行する
  19.      *
  20.      * @param string $fieldName
  21.      * @param array $options
  22.      * @return string
  23.      * @throws Exception
  24.      */
  25.     public function input($fieldName, $options = array())
  26.     {
  27.         foreach ($options as $key => $value) {
  28.             if (in_array($key, $this->app_tags)) {
  29.                 if (method_exists($this, $key)) {
  30.                     $options = call_user_func(array($this, $key), $options);
  31.                 } else {
  32.                     throw new Exception(sprintf('AppFormHelper::%s()がありません。', $key));
  33.                 }
  34.             }
  35.         }
  36.  
  37.         return parent::input($fieldName, $options);
  38.     }
  39.  
  40.     /**
  41.      * ヘルプの出力
  42.      *
  43.      * $options['help'] が 配列の場合 self::helpList()
  44.      * それ以外の場合 self::helpText() を実行する
  45.      *
  46.      * @param array $options
  47.      * @return array
  48.      */
  49.     protected function help(Array $options)
  50.     {
  51.         if (is_array($options['help'])) {
  52.             $options['helpList'] = $options['help'];
  53.             $options = $this->helpList($options);
  54.         } else {
  55.             $options['helpText'] = $options['help'];
  56.             $options = $this->helpText($options);
  57.         }
  58.         unset($options['help']);
  59.  
  60.         return $options;
  61.     }
  62.     /**
  63.      * 入力についての注意事項
  64.      *
  65.      * $options['helpText']の内容を pタグでラップして
  66.      * after に入れ替える
  67.      *
  68.      * @param array $options
  69.      * @return array
  70.      */
  71.     protected function helpText(Array $options)
  72.     {
  73.         $helptext = String::insert('<p class="help-text">:helptext</p>', array('helptext' => $options['helpText']));
  74.         if (array_key_exists('after', $options)) {
  75.             $options['after'] .= $helptext;
  76.         } else {
  77.             $options['after'] = $helptext;
  78.         }
  79.         unset($options['helpText']);
  80.  
  81.         return $options;
  82.     }
  83.  
  84.     /**
  85.      * 入力についての注意事項 複数
  86.      *
  87.      * $options['helpText']の内容を ulタグでラップして
  88.      * after に入れ替える
  89.      *
  90.      * @param array $options
  91.      * @return array
  92.      */
  93.     protected function helpList(Array $options)
  94.     {
  95.  
  96.         $ul = $this->Html->nestedList($options['helpList'], array('class' => 'help-list'));
  97.  
  98.         if (array_key_exists('after', $options)) {
  99.             $options['after'] .= $ul;
  100.         } else {
  101.             $options['after'] = $ul;
  102.         }
  103.         unset($options['helpList']);
  104.  
  105.         return $options;
  106.     }
  107.  
  108.     /**
  109.      * 入力例を追加
  110.      *
  111.      * $options['example']の内容を pタグでラップして
  112.      * after に入れ替える。inputタグの直後に表示される。
  113.      *
  114.      * @param array $options
  115.      * @return array
  116.      */
  117.     protected function example(Array $options)
  118.     {
  119.         $text = String::insert('<p class="example">入力例) :text</p>', array('text' => $options['example']));
  120.         if (array_key_exists('after', $options)) {
  121.             // 入力例はinputの直後に表示
  122.             $options['after'] = $text . $options['after'];
  123.         } else {
  124.             $options['after'] = $text;
  125.         }
  126.         unset($options['example']);
  127.  
  128.         return $options;
  129.     }
  130. }
  131. ?>

利用方法

下記のようにHTMLタグを含めることなく記述することができて、出力を変更したい場合、AppFormHelper を変更すれば済むようになります。

View/User/form.php

  1. <?php
  2. echo $this->Form->input('User.email', array(
  3.     'label'   => 'メールアドレス',
  4.     'example' => 'jousou@example.com',
  5.     'help'    => array(
  6.         '20文字以内で入力してください。',
  7.         '半角英数字で入力してください。'
  8.     )
  9. ));
  10. ?>
View/User/form.php

実行結果

  1.  
  2. <?php
  3. echo $this->Form->input('User.name', array(
  4.     'label'    => 'お名前',
  5.     'example'  => '内田靖人',
  6.     'helpText' => '20文字以内で入力してください。'
  7. ));
  8. ?>
  9.  
  10. <hr />
  11.  
  12. <?php
  13. echo $this->Form->input('User.email', array(
  14.     'label'    => 'メールアドレス',
  15.     'helpList' => array(
  16.         '20文字以内で入力してください。',
  17.         '半角英数字で入力してください。'
  18.     ),
  19.     'example'  => 'jousou@example.com',
  20. ));
  21. ?>
  22.  
  23. <hr />
  24.  
  25. <?php
  26. echo $this->Form->input('User.email', array(
  27.     'label'   => 'メールアドレス',
  28.     'help'    => array(
  29.         'aaaa',
  30.         'bbbb'
  31.     ),
  32.     'example' => 'jousou@example.com',
  33. ));
  34. ?>
  35.  
  36. <hr />
  37.  
  38. <?php
  39. echo $this->Form->input('User.email', array(
  40.     'label'   => 'メールアドレス',
  41.     'help'    => 'aaa',
  42.     'example' => 'jousou@example.com',
  43. ));
  44. ?>
  45.  
投稿日 2014年2月 3日 06:01
カテゴリ PHP
タグ CakePHP
トラックバック URL http://www.kantenna.com/cgi-bin/mt504/mt-tb.cgi/1348

コメント

コメントする
Name
Email Address
URL