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.

Upvotes: 0

Views: 341

Answers (1)

Cristian Bujoreanu
Cristian Bujoreanu

Reputation: 1167

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.

Upvotes: 1

Related Questions