複合ウィジェットの値の取得方法
symfonyのsfFormでは、「姓・名」という2つの入力欄を1つのウィジェットとしてまとめて扱うことができます。
このような場合、特定のウィジェットをsfWidgetFormSchemaでまとめたものを1つのウィジェットとして扱います。
同じように、バリデータもsfValidatorSchema内に対応するバリデータをまとめます。
「姓・名」という2つの入力フィールドを1つにまとめるサンプルは以下のようになります。
フォームクラス
// /lib/TestForm.class.php <?php class TestForm extends sfForm { public function configure() { // 名前欄用のウィジェットを準備する $name_widget = new sfWidgetFormSchema(array ( 'sei' => new sfWidgetFormInput(array('label'=>'姓')), 'mei' => new sfWidgetFormInput(array('label'=>'名')), ), array('label'=>'氏名')); // 名前欄用のバリデータを準備する $name_validator = new sfValidatorSchema(array ( 'sei' => new sfValidatorString(), 'mei' => new sfValidatorString(), )); // ウィジェットを設定する $this->setWidgets(array ( 'name' => $name_widget )); // バリデータを設定する $this->setValidators(array ( 'name' => $name_validator )); $this->widgetSchema->setNameFormat('test[%s]'); } }
アクション
// action.class.php <?php class testActions extends sfActions { public function executeTest_form(sfWebRequest $request) { $this->form = new TestForm(); if ($request->isMethod('post')) { $this->form->bind($request->getParameter('test')); if ($this->form->isValid()) { print_r($this->form->getValue('name')); // 入力値をダンプ } } } }
テンプレート
// test_formSuccess.php <form method="post" action="test_form"> <table> <?php echo $form; ?> </table> <input type="submit"> </form>
実行結果は以下のようになります。
# print_r の結果が配列になっています。
-
-
- -
-
追加:出力されたHTMLのテーブル部分
<table> <tr> <th>氏名</th> <td><tr> <th><label for="test_name_sei">姓</label></th> <td><input type="text" name="test[name][sei]" value="あいう" id="test_name_sei" /></td> </tr> <tr> <th><label for="test_name_mei">名</label></th> <td><input type="text" name="test[name][mei]" value="えおあ" id="test_name_mei" /></td> </tr> </td> </tr> </table>
このままだと若干おかしなタグ構造になってますね・・・><
さすがにこういうウィジェットの使い方をする場合は、テンプレート側も自動出力には頼れないようですね。