Ajax で Zend_Form を使用する方法に少し戸惑っています。コントローラーから呼び出される Zend_Form を拡張するクラスにフォームがあります。
GoodAddGroup.php
class Default_Form_GoodAddGroup extends Zend_Form {
(...)
public function init()
{
$this->setMethod('post');
$this->setAction("process-add-group");
$this->setName("addgroupgood");
// Load Elements class
require "Form/Elements.php";
$magElements = new Elements();
// Category
$categoryElement = $magElements->getCategorySelectField();
$categoryElement->setDecorators($this->elementDecorators);
// Barcode
$barcodeElement = $magElements->getGoodBarcodeTextField();
$barcodeElement->setDecorators($this->elementDecorators);
(...)
// Add elements to the form
$this->addElements(array(
$categoryElement,
//$codeElement,
$barcodeElement,
$serialElement,
$warehouseElement,
$submitButtonElement
));
$this->setDecorators($this->formDecorators);
}
}
GoodsController.php内
private function getAddGroupForm()
{
return new Default_Form_GoodAddGroup();
}
public function addGroupAction()
{
// Initialize the form for the view.
$this->view->form = $this->getAddGroupForm();
}
public function processAddGroupAction()
{
$form = $this->getAddGroupForm();
(...)
if ($_POST)
{
if ($form->isValid($_POST))
{
// Do things
} else {
$this->view->form = $form;
}
}
}
基本的に、フォームにはカテゴリ選択フィールドがあり、カテゴリを選択すると、このカテゴリに関連する項目で満たされた 2 番目の「コード」セレクターが追加されます。フォームのあるページ (http://myapp/goods/add-group) が表示されると、すべてが正常に機能し、ajax 呼び出しが機能し、2 番目の選択フィールドが追加されて適切に供給されますが、ご覧のとおり、フォーム処理は processAddGroupAction() で行われます。このメソッドはフォームのインスタンスを取得して値を取得し、問題が発生した場合に再表示します。しかし、そのようにすると、私の「新しい」選択フィールドはもう存在しないため、フォームを検証することはできません。
Zend で ajax/json を使用するのは初めての試みです。この時点で助けが必要だと思います。
ありがとうございました。
EDIT:要求に応じてビューコードを追加しました
<script>
$(function(){
$("#cats").change(function(){
getSelectBox(this);
});
$("#code").parent().parent().css('display', 'none');
getSelectBox($("#cats"));
});
function getSelectBox(element)
{
if($(element).val() != '')
{
$("#code").parent().parent().css('display', 'block');
if ($('#code').length <= 0) {
$("#cats").after('<select name="code" id="code" style="margin-left:10px"></select>');
}
$.getJSON("/goods/json-get-codes-from-category", {id: $(element).val(), ajax: "true"}, function(j){
console.log(j);
var options = "";
jQuery.each(j, function(i, val) {
options += '<option value="' + i + '">' + i + val + '</option>';
});
$("#code").html(options);
});
}
}
</script>
<?php echo $this->form; ?>