I want to solve insert/update in one controller. This is my code:
public function setOwnershipAction(Request $request) {
$session = $this->get('security.context')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
$game = $em->getRepository('GameShelfGamesBundle:Game')->find($request->request->get('hash'));
$user = $em->getRepository('GameShelfUsersBundle:User')->find($session->getId());
$typo = $em->getRepository('GameShelfUsersBundle:OwnState')->find($request->request->get('setownstate')['id']);
$plat = $em->getRepository('GameShelfGamesBundle:Platforms')->find($request->request->get('platformown')['id']);
$check = $em->getRepository('GameShelfUsersBundle:Own')->findBy(array(
'user' => $user,
'game' => $game
));
if(!$check) {
$own = new Own;
$own->setGame($game);
$own->setUser($user);
$own->setTypo($typo);
$own->setPlatforms($plat);
$own->setUpdated(date("Y-m-d H:i:s"));
$em->persist($own);
$em->flush();
} else {
$check->setTypo($typo);
$em->flush();
}
}
For now, insert (after if(!$check) turns true) works, but after else it just doesn’t click. My error is Fatal error: Call to a member function setTypo() on a non-object.
The
findBy()method will return an array. You need to usefindOneBy(), or loop through thefindBy()results.