Can't update existing Doctrine entity - symfony

I'm working with symfony 2.7 form component to update an entity called TapsAlert.
The problem, is the entity is not updated after submitting the form. I don't know what is going wrong. Here's a part of code:
public function editarRegistroAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$altd = $em->getRepository('ModeloBundle:TapsAlert')->find($id);
$altd->setAsunto($altd->getAsunto());
$altd->setGls($altd->getGls());
$altd->setDestinatario($altd->getDestinatario());
$altd->setPrts($altd->getPrts());
$altd->setTags($altd->getTags());
$altd->setValor($altd->getValor());
$form = $this->createFormBuilder($altd)
->add('Asunto', 'text')
->add('gls', 'text')
->add('destinatario', 'text')
//->add('dias', 'number')
->add('prts', 'text')
->add('Tags', 'text')
->add('valor', 'text')
->add('save', 'submit', array('label' => 'Guardar Cambios'))
->getForm();
//$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//$edAlert = $form->getData();
$em = $this->getDoctrine()->getManager();
//$em->persist($altd);
$em->flush();
return $this->redirect('http://192.168.1.128/');
}
return $this->render('MotoBundle:Default:edit.html.twig', array('form' => $form->createView()));
}
Thanks in advance.

First: this part of code is useless. It should be removed:
$altd->setAsunto($altd->getAsunto());
$altd->setGls($altd->getGls());
$altd->setDestinatario($altd->getDestinatario());
$altd->setPrts($altd->getPrts());
$altd->setTags($altd->getTags());
$altd->setValor($altd->getValor());
Second: You are not handling your request:
public function editarRegistroAction(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$altd = $em->getRepository('ModeloBundle:TapsAlert')->find($id);
$form = $this->createFormBuilder($altd)
->add('Asunto', 'text')
->add('gls', 'text')
->add('destinatario', 'text')
//->add('dias', 'number')
->add('prts', 'text')
->add('Tags', 'text')
->add('valor', 'text')
->add('save', 'submit', array('label' => 'Guardar Cambios'))
->getForm();
$form->handleRequest($request); //uncomment this line
if ($form->isSubmitted() && $form->isValid()) {
$em->flush();
return $this->redirect('http://192.168.1.128/'); // This url should an be an external url
}
return $this->render('MotoBundle:Default:edit.html.twig', array('form' => $form->createView()));
}
Third: I beleive that you can improve your code, with paramConvertor:
public function editarRegistroAction(Request $request, TapsAlert $tapsAlert){
$form = $this->createFormBuilder($tapsAlert)
->add('Asunto', 'text')
->add('gls', 'text')
->add('destinatario', 'text')
//->add('dias', 'number')
->add('prts', 'text')
->add('Tags', 'text')
->add('valor', 'text')
->add('save', 'submit', array('label' => 'Guardar Cambios'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirect('http://192.168.1.128/'); // This url should an be an external url
}
return $this->render('MotoBundle:Default:edit.html.twig', array('form' => $form->createView()));
}
It's a better practice, also, to build the form in a separate class, for more details, take a look to the official documentation https://symfony.com/doc/current/forms.html#creating-form-classes

Related

Symfony 6 App\Entity\Question object not found by the #ParamConverter annotation

I try to make answers for question.
Here is my AnswerController:
#[Route('/{slug}/{name}/answer/{question}', name: 'answer_question')]
public function answer(Question $q, QuestionRepository $questionRepository, string $question, Request $request, EntityManagerInterface $entityManager, string $slug, string $name, AnswerRepository $answerRepository): Response
{
$questions = $questionRepository->findOneBySlug($question);
$answers = $answerRepository->findAnswers($question);
$form = $this->createForm(AnswerType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$answer = new Answer();
$answer->setContent($data->getContent());
$answer->setAnsweredAt(new \DateTime);
$answer->setQuestion($q);
$entityManager->persist($answer);
$entityManager->flush();
return $this->redirectToRoute('show_question', [
'slug' => $slug,
'name' => $name,
'question' => $question,
]);
}
return $this->render('answer/index.html.twig', [
'questions' => $questions,
'answers' => $answers,
'answer' => $form->createView(),
]);
}
I have problem with
App\Entity\Question object not found by the #ParamConverter annotation
EDIT:
Still I have a little problem with wildcards,
for example when i put address "/audi-a3/8v/answer/question" it's ok, but when i put "/audi-a4/8v/answer/question" ( there isn't audi-a4 with model 8v but this address gives me correct page for "8V" model. It doesn't match ).
Can someone explain me how to do it right?
I did some changes in AnswerController and now it's working.
Set ParamConverter manually.
#[Route('/{car}/{name}/answer/{slug}', name: 'answer_question')]
#[ParamConverter('question', class: Question::class, options: ['mapping' => ['slug' => 'slug']])]
public function answer(Question $question, QuestionRepository $questionRepository, Request $request, EntityManagerInterface $entityManager, string $slug, string $name, string $car, AnswerRepository $answerRepository): Response
{
$questions = $questionRepository->findOneBySlug($slug);
$answers = $answerRepository->findAnswers($slug);
$form = $this->createForm(AnswerType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$answer = new Answer();
$answer->setContent($data->getContent());
$answer->setAnsweredAt(new \DateTime);
$answer->setQuestion($question);
$entityManager->persist($answer);
$entityManager->flush();
return $this->redirectToRoute('show_question', [
'slug' => $slug,
'name' => $name,
'car' => $car,
]);
}
return $this->render('answer/index.html.twig', [
'questions' => $questions,
'answers' => $answers,
'answer' => $form->createView(),
]);
}

How to pass correctly object using redirectToRoute?

This is my simple code
class LuckyController extends Controller
{
public function taskFormAction(Request $request)
{
$task = new Task();
//$task->setTask('Test task');
//$task->setDueDate(new \DateTime('tomorrow noon'));
$form = $this->createFormBuilder($task)
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class, array('label' => 'Save'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$task = $form->getData();
return $this->redirectToRoute('task_ok', array('task' => '123'));
}
return $this->render('pre.html.twig', array('pre' => print_r($task, true), 'form' => $form->createView()));
}
public function taskOKAction(Task $task)
{
return $this->render('ok.html.twig', array('msg' => 'ok', 'task' => print_r($task, true)));
}
}
and this line
return $this->redirectToRoute('task_ok', array('task' => '123'));
makes redirection to taskOKAction, but it lets me just send parameters by URL (?task=123).
I need to send object $task to taskOKAction to print on screen what user typed in form.
How can I do that? I've already red on stackoverflow before asking that the good solution is to store data from form (e.g. in database or file) and just pass in parameter in URL the ID of object. I think it's quite good solution but it adds me responsibility to check if user didn't change ID in URL to show other object.
What is the best way to do that?
Best regards,
L.
Use the parameter converter and annotate the route properly.
Something like (if you use annotation for routes)
/**
* #Route("/task/ok/{id}")
* #ParamConverter("task", class="VendorBundle:Task")
*/
public function taskOKAction(Task $task)
You can also omit the #ParamConverter part if parameter is only one and if is type hinted (as in your case)
From your form action you can do it without actual 302 redirect:
public function taskFormAction(Request $request)
{
$task = new Task();
//$task->setTask('Test task');
//$task->setDueDate(new \DateTime('tomorrow noon'));
$form = $this->createFormBuilder($task)
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class, array('label' => 'Save'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$task = $form->getData();
return $this-taskOKAction($task)
}
}
This is perfectly legal, and your frontend colleague will thank you for lack of the redirects.

Set current entity to an other

I work with symfony 2.8 and I have two entities : Cv and FormationCv ,
One Cv can have Many Formation Cv, so I try to do it with relation OneToMany and with collection Type
CvType
class CvForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//..
->add('formations', CollectionType::class, array(
'entry_type' => FormationCvForm::class,
'allow_add' => true,
'by_reference' => false,
)) ;
}
FormationCvType
class FormationCvForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('titre')
->add('etablissement')
->add('description')
->add('dateDebut', DateType::class, array(
'widget' => 'choice', 'translation_domain' => 'FOSUserBundle','data' => new \DateTime()))
->add('dateFin', DateType::class, array(
'widget' => 'choice',
))
;
}
Controller
public function createAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$cv = new Cv();
$form = $this->createForm('Front\FrontBundle\Form\CvForm', $cv);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user=$this->get('security.context')->getToken()->getUser();
$cv->setEtudiant($user);
$cv->setTelephone($user->getTel());
$cv->setDateNaissance($user->getBirthday());
$cv->setActif(false);
$em = $this->getDoctrine()->getManager();
$em->persist($cv);
$em->flush();
$formations=$cv->getFormations();
$formation= array();
foreach ($formation as $formations) {
$formation->setCv($cv->getId());
$em->persist($formation);
$em->flush();
}
return $this->redirectToRoute('cv_show', array('id' => $cv->getId()));
}
return $this->render("FrontBundle:CV:createCv.html.twig", array(
'form' => $form->createView(),
));
}
The problem that if I submit the form , in the table of FormationCv always get Null ,
Someone help me please ?
Your foreach is not going to run a single iteration:
$formations=$cv->getFormations();
$formation= array();
foreach ($formation as $formations) { // You're looping over $formation here, which is an empty array as per the line before this
$formation->setCv($cv->getId());
$em->persist($formation);
$em->flush();
}
Remove $formation= array(); and switch your variables in the foreach condition: foreach ($formations as $formation) {.
Alternatively/Preferably: Get rid of the whole block and let doctrine do the work by setting up your entities to cascade persist operations and telling it about the inverse-side (mappedBy / inversedBy).

Symfony and Doctrine - displaying data from database in controller method

This is my code. I want to set default value from database in the form. I want to set value in form which i create in this method.
public function updateBlogAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('AppBundle:Blog\Post')->find($id);
$blogs = new Post();
$form = $this->createFormBuilder($blogs)
->add('title', TextType::class, array('attr'=>array( 'class'=>'form-control','placeholder'=>'Blog title')))
->add('description', TextareaType::class, array('attr'=>array('class'=>'form-control','placeholder'=>'Blog description')))
->add('submit',SubmitType::class, array('label'=>'Add Blog', 'attr'=> array('class'=>'btn btn-primary pull-right')))
->getForm();
$form->handleRequest($request);
if( $form->isSubmitted() && $form->isValid() ){
$data->setTitle($blogs);
$em->flush();
return $this->redirectToRoute('blog');
}
return $this->render('blog/update_blog.html.twig', array(
'form' => $form->createView()
));
}
It is as easy as
$em = $this->getDoctrine()->getManager();
$blogs= $em->getRepository('AppBundle:Blog\Post')->find($id);
$form = $this->createFormBuilder($blogs)
/* ... */

persist in database is not working

i'm trying to add my data into my database , i was trying to not use a formbuilder, inside that i put all my form into the controller,
but when i submit the button i did't got an error but i can't find my data in the database.
here is my code any one have an idea please.
public function AjoutAction()
{
$classe=new Classes();
$formBuilder = $this->get('form.factory')->createBuilder('form', $classe);
$formBuilder
->add('NomClasse', 'text')
->add('save', 'submit')
;
$form = $formBuilder->getForm();
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($classe);
$em->flush();
} return $this->render('MyAppSchoolBundle:Classe:ajout.html.twig',array(
'form' => $form->createView(),
));
}
my twig file is here :
<h3>Formulaire d'annonce</h3>
{{ form(form) }}
thank you for your help
You need to change it to something like this:
public function AjoutAction(Request $request)
{
$classe=new Classes();
$formBuilder = $this->get('form.factory')->createBuilder('form', $classe);
$formBuilder
->add('NomClasse', 'text')
->add('save', 'submit')
;
$form = $formBuilder->getForm();
if ($form->handleRequest($request)->isValid()) {
$objToPersist = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($objToPersist);
$em->flush();
}
return $this->render('MyAppSchoolBundle:Classe:ajout.html.twig',array(
'form' => $form->createView(),
));
}

Resources