いくつかのテキストフィールドを持つZend_Formフォームがあるとしましょう。例:
$form = new Zend_Form();
$form->addElement('text', 'name', array(
'required' => true,
'isArray' => true,
'filters' => array( /* ... */ ),
'validators' => array( /* ... */ ),
));
$form->addElement('text', 'surname', array(
'required' => true,
'isArray' => true,
'filters' => array( /* ... */ ),
'validators' => array( /* ... */ ),
));
それをレンダリングした後、私は次のHTMLマークアップを持っています(簡略化):
<div id="people">
<div class="person">
<input type="text" name="name[]" />
<input type="text" name="surname[]" />
</div>
</div>
今、私は好きなだけ多くの人を追加できるようにしたいと思っています。Javascriptで次のdiv.personをコンテナに追加する「+」ボタンを作成します。フォームを送信する前に、たとえば5つの名前と5つの名前を配列としてサーバーに投稿します。誰かが検証しないフィールドに値を入力しない限り、すべてが正常です。次に、フォーム全体の検証が失敗し、フォームを再度表示したい場合(エラーあり)、PHPの警告が表示されます。
htmlspecialchars() expects parameter 1 to be string, array given
これは多かれ少なかれチケットに記載されています:http://framework.zend.com/issues/browse/ZF-8112
しかし、私はあまりエレガントではない解決策を思いつきました。私が達成したかったこと:
- すべてのフィールドと値をビューに再度レンダリングします
- 不正な値を含むフィールドの横にのみエラーメッセージが表示される
これが私の解決策です(スクリプトを表示):
<div id="people">
<?php
$names = $form->name->getValue(); // will have an array here if the form were submitted
$surnames= $form->surname->getValue();
// only if the form were submitted we need to validate fields' values
// and display errors next to them; otherwise when user enter the page
// and render the form for the first time - he would see Required validator
// errors
$needsValidation = is_array($names) || is_array($surnames);
// print empty fields when the form is displayed the first time
if(!is_array($names))$names= array('');
if(!is_array($surnames))$surnames= array('');
// display all fields!
foreach($names as $index => $name):
$surname = $surnames[$index];
// validate value if needed
if($needsValidation){
$form->name->isValid($name);
$form->surname->isValid($surname);
}
?>
<div class="person">
<?=$form->name->setValue($name); // display field with error if did not pass the validation ?>
<?=$form->surname->setValue($surname);?>
</div>
<?php endforeach; ?>
</div>
コードは機能しますが、これを行うための適切でより快適な方法があるかどうか知りたいですか?より動的な多値フォームが必要であり、長い間より良い解決策を見つけられなかったときに、私はしばしばこの問題にぶつかります。