我有3个未映射到FormType的下拉列表我正在绘制这些表单元素。
ContentType - 地区 - 语言
ContentType可以采用2个值 - 标准或区域。当我选择标准时,我不希望验证区域下拉列表。但是在选择Regional ContentType时应该验证它。区域和语言是动态填充的。
我无法遵循条件验证,我不认为这是我的方案的解决方案。
$brandId = $options['brandId'];
$builder
->add('contentType', 'choice', array(
'mapped' => false,
'empty_value' => 'Select Content Type',
'choices' => array(
'standard' => 'Standard',
'regional' => 'Regional'
),
'required' => true,
'multiple' => false,
'expanded' => false
))
->add('language', 'entity', array(
'required' => false,
'mapped' => false,
'empty_value' => 'Select Language',
'multiple' => false,
'class' => 'Bundle:Language',
'property' => 'title',
'query_builder' => function(EntityRepository $er) use($brandId) {
return $er->createQueryBuilder('l')
->join('l.regions', 'lr')
->join('lr.brands', 'lrb')
->where('lrb.id = :currentBrandId')
->setParameter('currentBrandId', $brandId);
}
))
->add('regionSelection', 'entity', array(
'required' => false,
'mapped' => false,
'empty_value' => 'Select Region',
'empty_data' => null,
'multiple' => false,
'class' => 'Bundle:Region',
'property' => 'title',
'query_builder' => function(EntityRepository $er) use($brandId) {
return $er->createQueryBuilder('r')
->join('r.brands', 'rb')
->where('rb.id = :currentBrandId')
->setParameter('currentBrandId', $brandId);
}
));
对此有任何帮助将不胜感激。
修改
所以我尝试使用回调向表单生成器添加约束:
->add('regionSelection', 'entity', array(
'constraints' => array(
new Assert\Callback(array(array($this, 'validateRegion')))
),
'mapped' => false,
'empty_value' => 'Select Region',
'empty_data' => null,
'multiple' => false,
'class' => 'Bundle:Region',
'property' => 'title',
'query_builder' => function(EntityRepository $er) use($brandId) {
return $er->createQueryBuilder('r')
->join('r.brands', 'rb')
->where('rb.id = :currentBrandId')
->setParameter('currentBrandId', $brandId);
}
));
电话如下:
public function validateRegion($value, ExecutionContextInterface $context)
{
//I am trying to check here if the contentType's selected value = 'regional' and no //region is selected then the following code executes.
$context->addViolationAt('regionSelection', 'There is already an event during this time!');
}
我现在的问题是因为我将$ this传递给回调函数,我找不到如何访问contentFormType字段。
答案 0 :(得分:2)
如果提交了其他字段,您可以检查全局$ _POST变量(通过Request对象)......似乎:
public function validateRegion($value, ExecutionContextInterface $context)
{
$request = Request::createFromGlobals();
$formData = $request->request->get("your_form_name");
if($formData["contentType"] == "regional"){
...
}
}