CakePHP
フォームヘルパーが生成するHTMLをカスタマイズする
テンプレートの作成 新しいテンプレートを「config」ディレクトリにfileName.phpとして作成する。このfileName.phpに、適用したいコードを追加していく。fileName.phpに記載されなかったものはデフォルトで設定されているものが適用される。 サンプル <?php return [ 'inputContainer' => '{{content}}', 'label' => '', 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}} class="form-control">', 'radioWrapper' => '{{input}}', ]; デフォルトで設定されているもの 'templates' => [ 'button' => '<button{{attrs}}>{{text}}</button>', 'checkbox' => ' <input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>', 'checkboxFormGroup' => '{{label}}', 'checkboxWrapper' => '<div class="checkbox">{{label}}</div>', 'dateWidget' => ' {{year}}{{month}}{{day}} {{hour}}{{minute}}{{second}}{{meridian}}', 'error' => '<div class="error-message">{{content}}</div>', 'errorList' => '<ul>{{content}}</ul>', 'errorItem' => '<li>{{text}}</li>', 'file' => '<input type="file" name="{{name}}"{{attrs}}>', 'fieldset' => '<fieldset{{attrs}}>{{content}}</fieldset>', 'formStart' => '<form{{attrs}}>', 'formEnd' => '</form>', 'formGroup' => '{{label}}{{input}}', 'hiddenBlock' => '<div style="display:none;">{{content}}</div>', 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}/>', 'inputSubmit' => '<input type="{{type}}"{{attrs}}/>', 'inputContainer' => ' <div class="input {{type}}{{required}}"> {{content}} </div>', 'inputContainerError' => ' <div class="input {{type}}{{required}} error"> {{content}}{{error}} </div>', 'label' => '<label{{attrs}}>{{text}}</label>', 'nestingLabel' => '{{hidden}}<label{{attrs}}>{{input}}{{text}}</label>', 'legend' => '<legend>{{text}}</legend>', 'multicheckboxTitle' => '<legend>{{text}}</legend>', 'multicheckboxWrapper' => '<fieldset{{attrs}}>{{content}}</fieldset>', 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>', 'optgroup' => ' <optgroup label="{{label}}"{{attrs}}> {{content}} </optgroup>', 'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>', 'selectMultiple' => ' <select name="{{name}}[]" multiple="multiple"{{attrs}}> {{content}} </select>', 'radio' => ' <input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>', 'radioWrapper' => '{{label}}', 'textarea' => ' <textarea name="{{name}}"{{attrs}}> {{value}} </textarea>', 'submitContainer' => '<div class="submit">{{content}}</div>', ] テンプレートの適用 App/View/AppViewに、以下のコードを記述する。 class AppView extends View { public function initialize() { $this->loadHelper('Form', [ 'templates' => 'fileName', ]); } } これを記述することで、イニシャライズされて、システム全体で自分が作成した新しいテンプレートが適用される。 部分的に適用させる フォームヘルパーを使用するところで、それぞれ適用させたいものを記載する。 サンプル <?php echo $this->Form->input('name', [ 'templates' => [ 'inputContainer' => '<div class="form-control">{{content}}</div>' ] ]); ?> それぞれのフォームヘルパーに記載しないといけないが、特定の場所の特定のタグにのみカスタマイズしたタグを生成することができる。