如何使用Symfony 2 FormBuilder禁用编辑视图中的字段

via*_*nes 17 php forms symfony twig

我用Symfony2 FormBuilder创建了一个表单,我想禁用编辑视图中的一个字段.我实际上是用包装器(display:none)隐藏它但是我想知道是否有更好的方法来做到这一点.我的代码如下所示:

的EntityType

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('fieldToDisabledInEditView');
    // ...
Run Code Online (Sandbox Code Playgroud)

EntityController

public function newAction() {
    $entity = new Entity;
    $form = $this->createForm(new EntityType, $entity);
    // ...
}
public function editAction() {
    $entity = new Entity;
    $form = $this->createForm(new EntityType, $entity);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

新(树枝)模板

<form>
    {{ form_row(form.fieldToDisabledInEditView) }}
    {# ... #}
Run Code Online (Sandbox Code Playgroud)

编辑(树枝)模板

<form>
    <span class="theValueOfTheHiddenField">{{ entity.fieldToDisabledInEditView }}</span>
    <div style="display:none">
        {{ form_row(form.fieldToDisabledInEditView) }}
    </div>
    {# ... #}
Run Code Online (Sandbox Code Playgroud)

Cer*_*rad 27

我想您会发现创建和编辑之间存在其他差异,尤其是验证组.由于您的控制器知道正在执行哪个操作,因此请考虑创建两个表单类型EditEntity和CreateEntity,然后使用公共库来最小化重复的代码.@cheesemackfly显示了如何向元素添加禁用属性.

但是当然你可能觉得有两种形式是浪费这么简单的差异.在这种情况下,为您的类添加意图标志并将其设置在控制器中

class EntityType
{
    public function __construct($intention)
    {
        $this->intention = $intention;

     ...
    // Use $this->intention to tweak the form

    }
}

// controller
$form = $this->createForm(new EntityType('create'), $entity);
OR
$form = $this->createForm(new EntityType('edit'), $entity);
Run Code Online (Sandbox Code Playgroud)

如果你真的想进入它,那么使用di注入意图.

 // controller
 $formType = $this->get('entity.create.formtype');
 OR
 $formType = $this->get('entity.edit.formtype');
Run Code Online (Sandbox Code Playgroud)

通过使用服务,您可以从一个表单类型开始,然后当您最终将其拆分为两个(您将)时,您的控制器仍将像以前一样工作.

还有一件事,假设您使用不同的模板进行编辑/创建,您实际上可以直接在twig中设置disabled属性.所以没有代码改变.

{{ form_row(form.yourField, { 'attr':{'disabled':'disabled'} }) }}
Run Code Online (Sandbox Code Playgroud)

================================================== ======================更新:2016年3月3日

万一有人偶然发现这一点,请注意Symfony 3不再支持让一个类实现多种表单类型.你基本上必须拥有单独的表单类型类,即使它们几乎完全相同.永远不要将实例数据添加到您的表单类型.

  • 谢谢你们(@cheesemacfly)。现在我只使用了 `{{ form_row(form.yourField, { 'attr':{'disabled':'disabled'} }) }}` 部分,但是很高兴知道如何修改表单类型无需复制表格。再次感谢,非常感谢:) (2认同)

che*_*fly 16

这是您可以将事件订阅者用于表单类的典型情况.
在你的情况下,它应该是:

// src/Acme/DemoBundle/Form/EventListener/AddfieldToDisabledInEditViewSubscriber.php
namespace Acme\DemoBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AddfieldToDisabledInEditViewSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        // Tells the dispatcher that you want to listen on the form.pre_set_data
        // event and that the preSetData method should be called.
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        // check if the object is "new"
        // If you didn't pass any data to the form, the data is "null".
        // This should be considered a new object
        if (!$data || !$data->getId()) {
            $form->add('fieldToDisabledInEditView');
        }
        else
        {
            $form->add('fieldToDisabledInEditView', null, array('disabled' => true));
            //If PHP >= 5.4
            //$form->add('fieldToDisabledInEditView', null, ['disabled' => true]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的表单类型:

// src/Acme/DemoBundle/Form/Type/EntityType.php
namespace Acme\DemoBundle\Form\Type;

// ...
use Acme\DemoBundle\Form\EventListener\AddfieldToDisabledInEditViewSubscriber;

class EntityType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('your_field');
        //...

        $builder->addEventSubscriber(new AddfieldToDisabledInEditViewSubscriber());
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html


小智 11

这种方法并不优雅,但我使用它因为很简单:

EntityController

public function newAction() {
    $entity = new Entity;
    $form = $this->createForm(new EntityType, $entity);
    // ...
}
public function editAction() {
    $entity = new Entity;
    $form = $this->createForm(new EntityType, $entity);
    $form->remove('fieldToDisabledInEditView');    
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Ego*_*eux 7

对于那些在 Symfony 3 中寻找解决方案而不创建单独的表单类型类(用于添加和编辑)并且不使用表单事件的人,您可以定义一个自定义选项并在创建时将其传递给表单:

我在表单类型类中创建了一个is_edit带有默认值的选项false

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => SomeEntity::class,
        'is_edit' => false
    ));
}
Run Code Online (Sandbox Code Playgroud)

您可以使用同一类$optionsbuildForm方法中的数组访问此选项:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('someField', TextType::class, array(
        'disabled' => $options['is_edit']
    ))
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以通过在表单创建时传递默认值来覆盖默认值:

$someForm = $this->createForm(
    SomeEntityType::class,
    $someEntity,
    array('is_edit' => true)
);
Run Code Online (Sandbox Code Playgroud)

https://symfony.com/doc/3.4/form/form_dependencies.html