场景:我有一个有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
}
}
Run Code Online (Sandbox Code Playgroud)
最初的类别是foo.因此foo的模板被加载并设置为选项.但是如果用户选择bar,则会加载条形模板.但表单仍然有foo选择,不会验证.
解决这个问题的最佳方法是什么?
我找到的一种方法是在控制器中重新启动表单:
<?php
$form = $this->createForm(new MyType());
if ($request->getMethod() === …Run Code Online (Sandbox Code Playgroud) 我尝试创建一个扩展核心" 实体 "类型的Symfony Custom 类型.
但是我想在Select2版本4.0.0中使用它(ajax现在可以使用"select"html元素,而不是像以前一样使用隐藏的"输入").
这通过设置选项(请参阅configureOption)来工作:
'choices'=>array()
Run Code Online (Sandbox Code Playgroud)
Select2识别html"select"的内容,并使用ajax工作.但是当表单被回发时,Symfony无法识别所选择的选项,(因为不允许这样做?)
Symfony\Component\Form\Exception\TransformationFailedException
Unable to reverse value for property path "user": The choice "28" does not exist or is not unique
Run Code Online (Sandbox Code Playgroud)
我尝试了几种使用EventListeners或Subscribers的方法,但我找不到工作配置.
使用Select2 3.5.*我解决了表单事件的问题并覆盖了隐藏的formtype,但是这里扩展实体类型要困难得多.
如何构建我的类型以让它管理我的entites的逆向转换?
自定义类型:
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
class AjaxEntityType extends AbstractType
{
protected $router;
public function __construct($router)
{
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{ …Run Code Online (Sandbox Code Playgroud)