1

Hi i am tying pass array collection (method getProjects() returns it) to form (select input) and fail. This code returns exception - A "__toString()" method was not found on the objects of type "Tasker\WebBundle\Entity\Project" passed to the choice field.

Can anybody help? Is needed transformer? Or what is right way?

Controller:

/**
 * @Route("/pridaj", name="web.task.add")
 * @Template()
 */
public function addAction(Request $request)
{

    $task = new Task;

    /** @var User $loggedUser */
    $loggedUser = $this->get('security.token_storage')->getToken()->getUser();

    $form = $this->createForm(new AddTaskType(), $task, ['user' => $loggedUser]);

    if ($form->handleRequest($request) && $form->isValid()) {

        // some stuff
    }


    return [
        'form' => $form->createView()
    ];
}

Form:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('project', 'entity', [
            'label' => 'Projekt:',
            'class' => 'TaskerWebBundle:Project',
            'choices' => $options['user']->getProjects(),
            'placeholder' => 'Označte projekt',
        ])
    // ....

 }


public function setDefaultOptions(OptionsResolverInterface $resolver)
{

    $resolver->setRequired(array(
        'user',
    ));

    $resolver->setDefaults(array(
        'user' => null,
    ));
}

2 Answers 2

2

just add __ToString() to your Project class

Tasker\WebBundle\Entity\Project

class Project
{
    ....

    function __toString() {
        return $this->getName(); //or whatever string you have
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I wanted to add another answer, because you do not have to add __toString() to your Project class. The Symfony entity field type allows you to specify which property/field to use for displaying. So instead of __toString() you could specify the property in the form configuration like so:

$builder
    ->add('project', 'entity', [
        'label' => 'Projekt:',
        'class' => 'TaskerWebBundle:Project',
        'choices' => $options['user']->getProjects(),
        'placeholder' => 'Označte projekt',
        'property' => 'name'
    ])

If you check this part of the Symfony documentation you will see that __toString() is automatically called only if you do not specify the property.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.