symfony setData() error - php

I'm trying to put a value in form created by formbuilder, i took the value from another twig file by the request, and i'm trying to use $form->setData(array('field'=>value));
Code controller:
public function ModifierGestionMatchAction(Request $request)
{
$id = $request->get('id');
$idmatch = $request->get('idm');
$em = $this->getDoctrine()->getManager();
$type = $em->getRepository("MainBundle:ReservationGestionStock")
->find($id);
$match = $em->getRepository("MainBundle:Match")
->findOneByid($idmatch);
$form = $this->createForm(ReservationGestionStockType::class, $type);
$form->setData(array('hotel'=>null));
$form->setData(array('match'=>$match));
$form->handleRequest($request);
if($form->isValid()){
$em->persist($type);
$em->flush();
return $this->redirectToRoute("ReservationGestionStockAfficher");
}
return $this->render('MainBundle:GestionStock:GestionStockModifierMatch.html.twig',
array(
"form" => $form->createView(),
"match" => $match
));
}
my form code:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('hotel',HiddenType::class)
->add('match',HiddenType::class)
->add('nb')
->add('nbr')
->add('Valider', SubmitType::class)
->add('Reset', ResetType::class);
}
Notice: the hotel and match are 2 entitys, i'm having problem with setData() for match, i tried to setdata of idmatch but its the same problem," the form isnt valid "

$form->get('hotel')->setData('John');
$form->get('match')->setData($match);

After submission just do that,
$type = $form->getData(); $type->setHotel($hotel); $type->setMatch($match); then persist and flush $type

i did this and its working, but i think it's so weird ... anyway thanks everyone for replying me.
if ($form->isSubmitted()) {
$gestion= new ReservationGestionStock();
$gestion->setMatch(null);
$gestion->setNb($form->getData()->getNb('nb'));
$gestion->setNbr($form->getData()->getNbr('nbr'));
$gestion->setHotel($hotel);
$em->persist($hotel);
$em->flush();
return $this->redirectToRoute("ReservationGestionStockAfficher");
}

Related

How to explain this issue and what should be the best solution about Symfony serializer/csv decoder

I am trying to make a simple CSV uploader with contacts and make them as array using Symfony serializer/CSV encoder. The problem is that when i get data from csv and i dump it i get everything fine i think. But when i want to loop over the array to echo email field or try to create new Objects and save them to database i get an error that index 'Email Address' is undefined. How that can be possible, if when i var_dump in a loop and die after first array on the list i see that 'Email Address' field exists.
Link to image - https://imgur.com/a/7bSJT0z
/**
* #Route("/upload-csv", name="upload")
*/
public function uploadCsv(Request $request)
{
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->getData();
$file = $data->getCsv();
//dump($file);
$serializer = $this->container->get('serializer');
$cons = $serializer->decode(file_get_contents($file), 'csv');
foreach ($cons as $con)
{
$contact = new Contact();
$contact->setEmail($con['Email Address']);
$contact->setFirstName($con['First Name']);
$contact->setLastName($con['Last Name']);
$contact->setCountry($data->getCountry());
$em->persist($contact);
}
$em->flush();
}
return $this->render('base.html.twig', [
'form' => $form->createView()
]);
}

I want to upload a profile picture with symfony2 and doctrine

In User.php (Entity name is User), I have a field in User entity named userPic , type String
In file UserType.php I mention userPic as shown below :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('userFullname')
->add('userName')
->add('userEmail')
->add('userPassword')
->add('userPic', 'file', array ('label'=>'profile Picture'))
->add('gender','choice',array('choices' => array('m' => 'Male', 'f' => 'Female')))
->add('isActive')
;
}
Now in the controller I'm getting the form fields as shown below
/**
* Creates a new User entity.
*
*/
public function createAction(Request $request)
{
$entity = new User();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('user_show', array('id' => $entity->getId())));
}
return $this->render('MWANRegisterBundle:User:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
Where do I have to give the path in which I want to save the picture? How can I save the uploaded file in my desired directory and save directory path in database?
Christian's answer is valid, however I'd just like to point out more specificaly how to do what is asked. Simply do :
if ($form->isValid()) {
$file = $form->getData()['file'];
$file->move('/your/path/to/your/file', 'yourFileName');
// Do the rest
...
}
Hope this helps.
You need to create an upload method in your entity. Check this link for more details http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
public function uploadFile()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
// use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->getFile()->move($this->getUploadDir(), $this->getFile()->getClientOriginalName());
// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = null;
}
/**
* Creates a new User entity.
*
*/
public function createAction(Request $request)
{
$entity = new User();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
// Upload file
$entity->uploadFile();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('user_show', array('id' => $entity->getId())));
}
return $this->render('MWANRegisterBundle:User:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}

Symfony FOS editing/updating username/email

Hello I'm trying to make user update/editing system with symfony FOSUserBundle and I have little problem
currently I'm able to load existing username and email with following code:
public function editAction(Request $request, $id)
{
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('id' => $id));
$form = $this-> createFormBuilder($user)
->add('username')
->add('email')
->add('save', 'submit')
->getForm();
$form->setData($user);
$userManager->updateUser($user);
return $this->render('PRACTestBundle:Default:edit.html.twig', array('form' => $form->creaveView()));
}
even though I'm able to submit form it won't save changes. Can someone help me out and tell how to do it? Thanks for your time!
It seems like you're mixing update action with edit page. I'm confused, why are you trying to update user just after loading data?
Here's how You should create controller with Show and Edit actions for currently logged user:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/ProfileController.php
If you're going to edit other user accounts, then change editAction from this URL to:
public function editAction(Request $request, $id)
{
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('id' => $id));
// the rest of the stuff
(...)
}
Let me know if this helps.
I solved this out..
public function editAction(Request $request, $id)
{
$userManager = $this->get('fos_user.user_manager');
$form = $this-> createFormBuilder($user)
->add('username')
->add('email')
->add('save', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid())
{
$userManager->updateUser($user);
}
return $this->render('PRACTestBundle:Default:edit.html.twig', array('form' => $form->creaveView()));
}

Var filled with object suddenly null, what happened?

I am building this form in symfony 2.0 and for some reason when I retrieve a object from the db and put it into an object it is gone when I want to save it so I get the following error:
Catchable Fatal Error: Argument 1 passed to MelvinLoos\CMS\CoreBundle\Entity\Page::setParent()
must be an instance of MelvinLoos\CMS\CoreBundle\Entity\Page, null given,
called in vendor\symfony\src\Symfony\Component\Form\Util\PropertyPath.php on line 347
and defined in src\MelvinLoos\CMS\CoreBundle\Entity\Page.php line 233
My code:
public function popupChildAction($parentid)
{
$entity = new Page();
$entity->setWebsite($this->getWebsite());
$parent = $this->getDoctrine()
->getRepository('MelvinLoosCMSCoreBundle:Page')
->findOneById($parentid);
if (!$parent)
{
throw $this->createNotFoundException('No parent found with given id: "' . $parentid . '"');
}
$entity->setParent($parent);
$entity->setCreatedBy($this->getUser());
//$entity->setPageType();
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
return $this->render('MelvinLoosCMSCoreBundle:Page:new_popup.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'parent' => $parent
));
}
As you can see I put in a if statement to check if $parent is filled and I also tried a var_dump to double check, it is defiantly filled with an object. But for some reason when I call the setParent() function of the entity object it fills it with null.
Melvin you have the check if the form is submitted and to get your entity from the form.
Can you try like this?
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$entity = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
}
Totally forgot that I had this question still floating around... Anyway I got around my problem, still don't know why I got the error but I solved it with quite a easy solution.
Instead of setting the parent for the child, I did the reverse and set the child for the parent. My code is the following (There is also new code in there that's irrelevant because I fixed it some time ago).
public function popupChildAction($parentid)
{
$parent = $this->getDoctrine()
->getRepository('MelvinLoosCMSCoreBundle:Page')
->findOneById($parentid);
if (!$parent)
{
throw $this->createNotFoundException('No parent found with given id: "' . $parentid . '"');
}
$entity = new Page();
$entity->setWebsite($this->getWebsite());
$entity->setCreatedBy($this->getUser());
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$parent->setChildren($entity);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
return $this->render('MelvinLoosCMSCoreBundle:Page:new_popup.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'parent' => $parent
));
}
Like I said there is newer code that is irrelevant but what it's all about is the part with
$parent->setChildren($entity); and now it works... hope this helps someone!
Thanks for everyone that gave input!

Symfony2 How to process dynamic embed forms collection?

I try this cookbook about embed form:
http://symfony.com/doc/current/cookbook/form/form_collections.html
But the embed foreign key (task_id field in Tag table) is not save, always NULL
Here the complete code: https://gist.github.com/1755140
Do you know why?
Thank
Edit::
My trouble was in process form action. Like the tag form is embed dynamically, so i don't know how many tag(s) i will have. If i add in createAction
$tag1 = new Tag();
$task->addTags($tag1);
only the first embed form was correctly save! How to save the other tags?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit2:
My solution which resolve the trouble, what do you think about it? Better?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit3:
A much better alternative (not tested again)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
In TaskController on line 29 try to use $task->addTags($tag1); instead of $task->getTags()->add($tag1);
I don't understand. Is this solution wrong?
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
foreach($task->getTags() as $tag) {
$tag->setTask($task);
}
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
It works and it seems simpler.

Categories