Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: how to get the Type that a form is constructed from

Tags:

forms

symfony

I'm trying to dynamically generate my forms based on the user's permissions for that I have created a extension which adds listeners to forms and filters their fields accordingly.this works just fine However I'm having trouble with getting the typeName (returned from the getName method for classes which implement the FormTypeInterface) of each field (which is FormInterface).I've tried FormInterface::getName but that returns the field name that is given to the builder e.g: $builder->add('fieldName',new FooType()) when I call getName on a FormInterface that is constructed like this I get "fieldName".What I want is the returned value from FooType::getName.How can I do that?I have also checked FormInterface->getConfig->getName() but that also gave the same same Result.the code for the listener:

class FooListener implements EventSubscriberInterface{
public static function getSubscribedEvents()
{
    //set low priority so it's run late
    return array(
        FormEvents::PRE_SET_DATA => array('removeForbiddenFields', -50),
    );
}

public function removeForbiddenFields(FormEvent $event){

    $form = $event->getForm();

    $formName = $form->getName();/*what I want for this is to return the name of the
    type of the form.e.g: for the field that is construced with the code below 
    it must return FooType::getName*/

    $fields = $form->all();

    if($fields){
        $this->removeForbiddenFormFields($form, $formName, $fields);
    }
}
}

class barType extends AbstractType{   

public function buildForm(FormBuilderInterface $builder, array $options){
    $builder->add('fieldName',new FooType());
}
....

}
like image 861
user2268997 Avatar asked Nov 15 '25 19:11

user2268997


1 Answers

For those of you using Symfony 3 this can now be done with:

$formClass = $form->getConfig()->getType()->getInnerType();

$formClass will be a stdClass representation of the class itself (not the instance of it though), and you can use get_class($formClass) to get a string for its FQCN, e.g. "App\Form\Type\SillyFormType".

I've not tested this on Symfony 4, though it'll likely be the same.

like image 77
Adambean Avatar answered Nov 18 '25 20:11

Adambean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!