Issue
I have two entities called, Ticket & TicketUpdate. Each Ticket can have many TicketUpdates, but every TicketUpdate can only have 1 Ticket.
Next I have a form which shows the current Ticket, but also allows me to add 1 TicketUpdate & change attributes of Ticket.
This is my controller:
//TicketController.php
...
/**
 * @Route("/ticket/{id}", name="app_ticket")
 */
public function ticket(Request $request, Ticket $ticket)
{
    $ticketUpdate = new TicketUpdate();
    $ticketUpdate->setTicket($ticket);
    $form = $this->createForm(TicketUpdateType::class, $ticketUpdate); //custom form type
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($ticketUpdate);
        $em->persist($ticket);
        $em->flush();
    }
    return $this->render('ticket/view.html.twig', ['ticket' => $ticket, 'form' => $form->createView()]);
}
...
TicketUpdateType:
//TicketUpdateType.php
...
class TicketUpdateType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('text', TextareaType::class, ['label' => 'update', 'required' => false, 'attr' => ['class' => 'textarea-sm'])
            ->add('ticket', TicketType::class, ['label' => false, 'by_reference' => false]) //custom Type for Tickets
            ->add('submit', SubmitType::class, ['label' => 'save']);
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => TicketUpdate::class
        ]);
    }
}
...
However, this solution does not work for me. Symfony always wants to create a new Ticket entry, instead of changing the old one.
Is there any way to fix this?
Solution
Update: I changed by_reference to true and removed every logic in my TicketType, which seemed to cause the issue.
Atleast for now I got it running. Here is my controller:
//TicketController.php
...
/**
 * @Route("/ticket/{id}", name="app_ticket")
 */
public function ticket(Request $request, Ticket $ticket)
{
    $ticketUpdate = new TicketUpdate();
    $ticketUpdate->setTicket($ticket);
    $form = $this->createForm(TicketUpdateType::class, $ticketUpdate); //custom form type
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($ticketUpdate);
        //$em->persist($ticket); -> removed, will be automatically updated by symfony
        $em->flush();
    }
    return $this->render('ticket/view.html.twig', ['ticket' => $ticket, 'form' => $form->createView()]);
}
...
Answered By - Syllz
 
 Posts
Posts
 
 
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.