0
votes

I'm getting following exception, when I try to add a task and automaticly add the current user to the accordion field of the task:

Catchable Fatal Error: Argument 1 passed to Seotool\MainBundle\Entity\Task::setUser() must be an instance of Seotool\MainBundle\Entity\User, string given, called in /Applications/MAMP/htdocs/Seotool/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 438 and defined in /Applications/MAMP/htdocs/Seotool/src/Seotool/MainBundle/Entity/Task.php line 174

My Controller looks like this:

/**
@Route(
 *     path = "/taskmanager/user/{user_id}",
 *     name = "taskmanager"
 * )
 * @Template()
 */
public function taskManagerAction($user_id, Request $request)
{

/* #### NEW TASK FORM #### */

$task = new Task();

$addTaskForm = $this->createForm(new TaskType(), $task);

$addTaskForm->handleRequest($request);

if($addTaskForm->isValid()):

    $task->setDone(FALSE);
    $task->setUser($user_id);
    $task->setDateCreated(new \DateTime());
    $task->setDateDone(NULL);

    $em = $this->getDoctrine()->getManager();
    $em->persist($task);
    $em->flush();

    return $this->redirect($this->generateUrl('taskmanager', array('user_id' => $user_id)));

    endif;

Line 174 in Entity/Task.php:

/**
 * Set User
 *
 * @param \Seotool\MainBundle\Entity\User $user
 * @return Task
 */
public function setUser(\Seotool\MainBundle\Entity\User $user = null)
{
    $this->User = $user;

    return $this;
}

Does anybody know how to set the value for my hidden "user" form field with $user_id value?

Thanks in advance

1
Please don't accept answer without leave a comment: what solution did you followed and why? Comment under my answer please as it has two possibility:) - DonCallisto

1 Answers

0
votes

You can't do

$task->setUser($user_id);

because $user_id, here, is a string and your method signature expects an object of Seotool\MainBundle\Entity\User type.

You can proceed in two ways, depending on your needs (but I suppose that only second option will be suitable for you):

1) Modify your setUser() function if you don't need a reference (ORM oriented) or User Object into your Task Object

public function setUser($user = null)
{
    $this->User = $user;

    return $this;
}

2) Retrieve current user and set it

public function taskManagerAction($user_id, Request $request)
{

[...]

if($addTaskForm->isValid()):

    $user = $this->get('security.context')->getToken()->getUser();
    $task->setUser($user);
    [...]
    endif;

$this->get('security.context')->getToken()->getUser(); gives you current logged user but, maybe, you need to change signature aswell (possible inheritance issues?)