gpt4 book ai didi

php - Symfony2 : Change choices with ajax and validation

转载 作者:IT王子 更新时间:2023-10-28 23:58:08 29 4
gpt4 key购买 nike

场景:我有一个包含 2 个选择的表单。当用户从第一个选择中选择某些内容时,第二个选择会填充新值。这部分工作正常。

但是表单没有得到验证,因为它包含一些初始表单中不允许的选项。

表格:

<?php

class MyType extends AbstractType
{
private $category;

public function __construct($category = null)
{
$this->category = $category;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('category', 'choice', array(
'choices' => array(
'foo' => 'foo',
'bar' => 'bar'
)
);

$builder->add('template', 'choice', array(
'choices' => $this->loadChoices()
);
}

private function loadChoices()
{
// load them from DB depending on the $this->category
}
}

最初类别是foo。因此 foo 的模板被加载并设置为选项。但是如果用户选择 bar,就会加载栏模板。但是表单仍然有 foo 选项并且不验证。

解决这个问题的最佳方法是什么?

我发现的一种方法是在 Controller 中重新启动表单:

<?php

$form = $this->createForm(new MyType());

if ($request->getMethod() === 'POST') {
if ($request->request->has($form->getName())
&& isset($request->request->get($form->getName())['category'])) {
$form = $this->createForm(new MyType($request->request->get($form->getName())['category']));
}

// ...
}

这行得通,但我无法测试它,因为它在设置值时抛出 IllegalArgumentException 并且只是假定默认值。对此有更好的解决方案吗?提前致谢!

最佳答案

我认为你必须使用事件来管理它,这是更正确的方法

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('category', 'choice', array(
'choices' => array(
'foo' => 'foo',
'bar' => 'bar'
)
));

$ff = $builder->getFormFactory();

// function to add 'template' choice field dynamically
$func = function (FormEvent $e) use ($ff) {
$data = $e->getData();
$form = $e->getForm();
if ($form->has('template')) {
$form->remove('template');
}

$cat = isset($data['category'])?$data['category']:null;

// here u can populate ur choices in a manner u do it in loadChoices
$choices = array('1' => '1', '2' => '2');
if ($cat == 'bar') {
$choices = array('3' => '3', '4' => '4');
}

$form->add($ff->createNamed('template', 'choice', null, compact('choices')));
};

// Register the function above as EventListener on PreSet and PreBind
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
$builder->addEventListener(FormEvents::PRE_BIND, $func);
}

关于php - Symfony2 : Change choices with ajax and validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13321771/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com