【CakePHP】フォームヘルパーでデフォルトのオプションを設定
バージョン:CakePHP 2.x
フォームヘルパーはデフォルトでdviタグやlabelを出力します。
dviタグやlabelを出力したくない場合はオプションでfalseを設定するのですが、
全てのフォームヘルパーに設定をするのが大変な場合には「inputDefaults」で、
デフォルトの設定を決めることができます。
オプションなしの場合
inputDefaultsを設定しない場合です。
1 2 3 4 5 | <?php echo $this ->Form->create( 'User' ); ?> <?php echo $this ->Form->input( 'test1' ); ?> <?php echo $this ->Form-> end ( 'てすと' );?> |
出力は下記のようになり、labelやdivタグが出力されます。
1 2 3 4 5 6 7 8 | < form action = "/cakephp-2.4.7/users" id = "UserIndexForm" method = "post" accept-charset = "utf-8" > < div style = "display:none;" >< input type = "hidden" name = "_method" value = "POST" /></ div > < div class = "input text" > < label for = "UserTest1" >Test1</ label > < input name = "data[User][test1]" type = "text" id = "UserTest1" /> </ div > < div class = "submit" >< input type = "submit" value = "てすと" /></ div > </ form > |
inputDefaultsを設定
下記例ではオプションのinputDefaultsで、labelとdivタグを出力しないように設定をしています。
1 2 3 4 5 6 7 8 9 | <?php echo $this ->Form->create( 'User' , array ( 'inputDefaults' => array ( 'label' => false, 'div' => false ) )); ?> <?php echo $this ->Form->input( 'test1' ); ?> <?php echo $this ->Form-> end ( 'てすと' );?> |
出力は下記のような形になります。
1 2 3 4 | < form action = "/cakephp-2.4.7/users" id = "UserIndexForm" method = "post" accept-charset = "utf-8" > < div style = "display:none;" >< input type = "hidden" name = "_method" value = "POST" /></ div > < input name = "data[User][test1]" type = "text" id = "UserTest1" /> </ form > |
inputDefaults設定したがlabelを出力したい場合などには、
「array('label’ => 'Username’)」などとして個別に出力が可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php echo $this ->Form->create( 'User' , array ( 'inputDefaults' => array ( 'label' => false, 'div' => false ) )); ?> <?php echo $this ->Form->input( 'test2' , array ( 'label' => 'Username' ) ); ?> <?php echo $this ->Form-> end ( 'てすと' );?> |
1 2 3 4 5 6 | < form action = "/cakephp-2.4.7/users" id = "UserIndexForm" method = "post" accept-charset = "utf-8" > < div style = "display:none;" >< input type = "hidden" name = "_method" value = "POST" /></ div > < label for = "UserTest2" >Username</ label > < input name = "data[User][test2]" type = "text" id = "UserTest2" />< div class = "submit" > < input type = "submit" value = "てすと" /></ div > </ form > |
参考:CakePHP公式サイト