Symfony2获取禁用表单字段的值(或将它们全部标记为未禁用)

时间:2015-01-08 15:18:59

标签: forms symfony

我的情况是,在我的树枝中,我动态地将一些表单字段设置为禁用或不禁用。

当我提交时,我需要启用所有字段,否则字段值为空(有关类似问题,请参阅here)。我的问题是我的表单比示例中的表单更复杂。

这是:

<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HRMgmtFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$rolesListForForm = $options['data']['rolesListForForm'];
$HRsInThisProject = $options['data']['HRsInThisProject'];
$HRsInMyDomainForForm = $options['data']['HRsInMyDomainForForm'];    

$builder->add('showinactive', 'checkbox', array('label' => 'Show inactive users', 'required'  => false, 'data' => true, ));
foreach ($HRsInThisProject as $key => $HR)
    {
    $builder->add('roleOf_'.$key, 'choice', array('choices'   => $rolesListForForm, 'required'  => true, 'data' => $HR['role'], 'label' => false, ))
            ->add('isActive_'.$key, 'choice', array('choices'   => [0 => 'Inactive', 1 => 'Active'] , 'required'  => true, 'data' => $HR['is_active'], 'label' => false, ));
    }
$builder->add('HRid', 'choice', array('choices' => $HRsInMyDomainForForm,'required' => false, 'placeholder' => 'Choose a resource', 'label' => false, ));
$builder->add('role', 'choice', array('choices' => $rolesListForForm,'required' => false, 'placeholder' => 'Choose a role', 'label' => false, ));            
$builder->add('save', 'submit', array('label' => 'Save'));  

//this is what is suggested in the link I mentioned
$builder->addEventListener(
        FormEvents::PRE_SUBMIT,
        function(FormEvent $event) {
            $event->getForm()->add( // some stuff //, array(
                // more stuff //
                'disabled' => false
            ));
        }
    );
}

public function getName()
{
    return 'MRMgmt';
}
}

在我的树枝上,我做了类似的事情:

{% for key, HR in HRs %}
...
{% if role.OthersProfileChangeSecurityRightsRoles %}
   {{ form_row(form['roleOf_' ~ key]) }}
{% else %}
   {{ form_row(form['roleOf_' ~ key], { 'attr':{'disabled':'disabled'}}) }}
{% endif %}

我想知道:有没有办法以另一种方式解决问题? 或者我可以遍历所有字段并将其标记为“禁用&#39; =&gt; false,而无需基本上重新创建整个表单,这似乎是一种矫枉过正(我不知道我是否还有访问我需要做的所有变量)? 也许一个解决方法是创建隐藏字段而不是禁用字段,并在我的树枝中打印字段的值而不是禁用的字段......

谢谢!

0 个答案:

没有答案