I wrote a function in BudgetRepository
that is called when inserting new data into Budget table. The function is:
public function addBudgetToClient($clientId, $budgetId)
{
return $this->createQueryBuilder('b')
->update('PanelBundle:Client', 'c')
->set('c.budget', $budgetId)
->where('c.id = ' . $clientId)
->getQuery()
->execute();
}
And the BudgetController
does this:
public function addAction(Request $request)
{
$form = $this->createForm(new BudgetType());
$manager = $this->getDoctrine()->getManager();
$Budget = $manager->getRepository('PanelBundle:Budget');
$Client = $manager->getRepository('PanelBundle:Client');
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$manager->persist($form->getData());
$manager->flush();
// Here's the method:
$Budget->addBudgetToClient($form['client_id']->getData()->getId(), $Budget->getLastId());
//
$this->addFlash('success', 'Novo orçamento adicionado');
return $this->redirect($this->generateUrl('panel_budgets'));
}
}
return $this->render('PanelBundle:Budget:add.html.twig', array(
'clients' => $Client->findAll(),
'form' => $form->createView()
));
}
I tested both outputs, the getLastId
is also a custom function I wrote to retrieve the biggest ID from Budget, and the $form['client_id']->getData()->getId()
also retrieves the Client id. I guess Symfony2 automatically does something because Budget and Client are related, and even saving the Client id, in the database shows the Client name, I don't understand how actually.
The issue here are these errors:
[Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
[2/2] QueryException: [Semantical Error] line 0, col 34 near 'budget = 4 WHERE': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected. +
[1/2] QueryException: UPDATE PanelBundle:Client c SET c.budget = 4 WHERE c.id = 1 +
I found many problems about this exception but they haven't had it with update
function, only select
.
You should not build an update query for this case using a queryBuilder. Use OOP approach to update your entities.