简体   繁体   中英

Disabling a text box depending of a condition in symfony formType

I'm pretty new in Symfony2 and I have a problem with a form type.

I have the table 'messages' in the data base and every message have an id, message and owner.

Then, I have to show these messages inside a forms. So I do this:

->add('shortComment', 'text', array(
            'label' => 'Short Message',
            'data' => $this->_predefinedMessage->getShortComment()))

So, the problem for me is when I want to disable this text box when:

owner != currentUser

I don't know how to preceed. I will apreciate any help.

Thanks a lot.

A solution would be to send $disabled field into the form, but initialize it inside your controller:

$disabled = $owner == $currentUser ? false : true;

$form = $this->createForm(new YourFormType($disabled), $messageEntity);

In YourFormType.php

class YourFormType extends AbstractType
{
    protected $disabled;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('shortComment', 'text', array(
            'label' => 'Short Message',
            'disabled' => $this->disabled
        ));    
    }

}

I hope this is useful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM