0

i'm creating an own form type in symfony2 but i cannot access my own defaultOptions in the buildView function. Here is the code:

public function getDefaultOptions(array $options)
{        
    return array(
        'identifier' => isset($options['identifier']) ? $options['identifier'] : '#star',
        'currentRating' => isset($options['currentRating']) ? $options['currentRating'] : 0,
    );
}

/**
 * {@inheritdoc}
 */
public function buildView(FormView $view, FormInterface $form)
{                
    $view->set('currentRating', $form->getAttribute('currentRating'));
    $view->set('idientifier', $form->getAttribute('identifier'));
}

The error:

Notice: Undefined index: currentRating in ...

I don't read anything that this is not possible. Thank you for your help.

2 Answers 2

3

In the method buildForm of your type, you need to set explicitly the attribute you want to use in the method buildView. Here is how you should do it:

public function buildForm(FormBuilder $builder, array $options)
{
    // Code here

    $builder->setAttribute('currentRating', $options['currentRating']);
    $builder->setAttribute('identifier', $options['identifier']);
} 

public function buildView(FormView $view, FormInterface $form)
{
    $view->set('currentRating', $form->getAttribute('currentRating'));
    $view->set('identifier', $form->getAttribute('identifier'));
}

This should do the trick. Hope this helps.

Regards,
Matt

0

@Matt's answer is great but just a notice for anyone using Symfony 2.1+:

A third argument was added (https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md) to buildView called array $options which is required so make sure you add this.

So if you're using Symfony 2.1+ do this:

public function buildForm(FormBuilder $builder, array $options)
{
    // Code here

    $builder->setAttribute('currentRating', $options['currentRating']);
    $builder->setAttribute('identifier', $options['identifier']);
} 

public function buildView(FormView $view, FormInterface $form, array $options)
{
    $view->set('currentRating', $form->getAttribute('currentRating'));
    $view->set('identifier', $form->getAttribute('identifier'));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.