Symfony - controller edit action - php

I defined the form in my controller and set function to edit/update specific fields that I can find by ID. I can't find what am I doing wrong..
public function getUserEdit(Request $request)
{
$form = $this->createFormBuilder()
->add('firstName', TextType::class, array('label' => 'First Name*', 'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array('label' => 'Send', 'attr' => [
'class' => 'btn btn-primary action-save'
]))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$firstName = $data['firstName'];
$this->container->get('user')->editUser($firstName);
}
return $this->success();
}
Service
public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if(empty($editUsers)) {
$editUsers = new User();
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
}

Symfony returns a single object when searching by find primary key (usually id), then you can check if exist returns a single Entity (in this case User) and so that checking by using insteance.
public function editUser($id)
{
$editUsers = $this->getUserRepository()->find($id);
if($editUsers insteance User) { // here just check
//$editUsers = new User(); // here You don't need create new object of class User, just remove
$editUsers->setId($id);
$this->em->persist($editUsers);
$this->em->flush();
}
else {
// do something if you need
}
}

Related

Symfony 4, when I try to submit a form it does not work

Thanks in advance to those who want to help me. I'm learning symfony 4 and I'm testing to see how to update a database by taking data from a form. So I made sure that it looked for a table on the base of the id and that it filled the form with the correct values ​​of the form. But when I submit, the form-> isSubmitted condition is never verified. Do you have any suggestions?
public function updateArticle(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository(Article::class)->find($id);
if (!$article) {
throw $this->createNotFoundException(
'No article found for id '.$id
);
}
$articletext = $article->getArticle();
$title = $article->getTitle();
$image = $article->getFeatureimage();
$category = $article->getCategory();
$author = $article->getAuthor();
$article->setArticle($articletext);
$article->setTitle($title);
$article->setFeatureimage($image);
$article->setCategory($category);
$article->setAuthor($author);
$form = $this->createFormBuilder($article)
->add('article', TextareaType::class)
->add('title', TextType::class)
->add('featureimage', FileType::class, array('data_class' => null,'required' => true))
->add('category', TextType::class)
->add('author', TextType::class)
->add('save', SubmitType::class, array('label' => 'Inserisci articolo'))
->getForm();
if ($form->isSubmitted()) {
$article = $form->getData();
print_r($article);
return $this->redirectToRoute('blog');
}
else
return $this->render('insert.html.twig', array(
'form' => $form->createView(),
));
}
Your forgot a line that handle the data.
Look at the doc
Add this line before the if condition:
//form creation as you did but it's better to construct the form via the FormType
$form->handleRequest($request);
if ($form->isSubmitted()){
//Do some stuff

Best practice for changing default parameter of form object after getForm() symfony2.8

I updated and summurized the question.
What I want to do is changing the default value of form object after getForm()
public function newAction(Request $request)
{
$task = new Task();
$form = $this->createFormBuilder($task)
->add('task', TextType::class,array('data' => 'default text data') // Set the default data for loaded first time.
->add('save', SubmitType::class, array('label' => 'Save'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//I want change the default value of task, I tried a few methods.
$d = $form->getData();
$form->get('task')->setData('replace text data'); // not work
$d->setData('second data'); // notwork
}
Is it possible or how??
Try this one.
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $even) {
$data = $event->getData();
$form = $event->getForm();
if (isset($data['task'])) {
$data['task'] = "Default Task1";
$event->setData($data);
}
});

Symfony 2 isClicked on submit buttons always returning FALSE

I'm trying to implement two submit buttons to my form. My form looks something like this.
Form:
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options) {
$builder
// ...
->add('gateway', 'submit', array(
'label' => 'Go to payment gateway',
))
->add('save', 'submit', array(
'label' => 'Save order',
));
parent::buildForm($builder, $options);
}
Method $form->get('save')->isClicked() in controller always returning FALSE . It doesn't depend on which button I click in form, everytime returns FALSE.
Controller:
public function indexAction(Request $request) {
$form = $this->createForm(new OrderForm(null));
$form->handleRequest($request);
if ($form->isValid()) {
$values = $form->getData();
$action = $form->get('save')->isClicked() ? 'front.order.success' : 'front.order.gateway';
if ($action == 'front.order.success') {
//save order
} else if ($action == 'front.order.gateway') {
//something else
}
}
return $this->redirect($this->generateUrl($action));
}
Have you any idea why? Thank you for answers.

populate select field on another select's "change" event in symfony2 and make it OK for submission

Using Symfony2.3.4 and PHP5.6.3
People, I've been looking for this issue for a while now and yes, I've found some similar ones and even found this in the Cookbook.
Now you'd say, "This guy is pretty slow", bingo, I am. Please help me out because I can't seem to get this or any other example I've encountered to help me in my own problem.
What I need is to populate a select field when the user selects an item from another select field. All this happens in a standard-CRUDgenerated-Symfony2 form. Both selects stand for an entity collection each(Zone and UEB), being Zone the independent one.
Community: Stop talking and give me the code!
Me: OK, here is what I have so far:
//ReferenceController.php
public function newAction() {
$entity = new Reference();
$form = $this->createCreateForm($entity);
return $this->render('CCBundle:Reference:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
public function createAction(Request $request) {
$entity = new Reference();
$form = $this->createCreateForm($entity);
$form->bind($request);
/*
var_dump($form->get('UEB')->getData());
var_dump($form->get('UEB')->getNormData());
var_dump($form->get('UEB')->getViewData());
die();
*/
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('reference_show', array('id' => $entity->getId())));
}
return $this->render('CCBundle:Reference:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
private function createCreateForm(Reference $entity) {
$form = $this->createForm(new ReferenceType(), $entity, array(
'action' => $this->generateUrl('reference_create'),
'method' => 'POST',
));
return $form;
}
And
//ReferenceType.php
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('suffix')
->add('zone', null, array(
'required' => true,
))
;
//What follows is for populating UEB field accordingly,
//whether it's a "createForm" or an "editForm"
if ($options['data']->getId() !== null) {
$formModifier = function (FormInterface $form, Zone $zone = null) {
$UEBs = null === $zone ? array() : $zone->getUEBs();
$form->add('UEB', 'entity', array(
'required' => true,
'label' => 'UEB',
'class' => 'CCBundle:UEB',
// 'empty_value' => '',
'choices' => $UEBs,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getZone());
});
} else {
$formModifier = function (FormInterface $form) {
$form->add('UEB', 'entity', array(
'required' => true,
'label' => 'UEB',
'class' => 'CCBundle:UEB',
'query_builder' =>
function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.zone = :zone')
->setParameter('zone', $er->findFirstZone());
}
)
);
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
$formModifier($event->getForm());
});
}
And
//base.js
var goalURL = "" + window.location;
if (goalURL.slice(-13) === 'reference/new' || goalURL.match(/reference\/\d+\/edit$/))
{
//case new reference
goalURL = goalURL.replace('reference/new', 'reference/update_uebs/');
//case edit reference
goalURL = goalURL.replace(/reference\/\d+\/edit/, 'reference/update_uebs/');
//this is the function run every time the "new" or "edit" view is loaded
//and every time the Zone select field is changed
var runUpdateUEBs = function() {
$.getJSON(goalURL, {id: $('#cc_ccbundle_reference_zone').val()}, function(response) {
$('#cc_ccbundle_reference_UEB').children('option').remove();
var non_selected_options = [];
var index = 0;
$.each(response, function(key, val) {
var option = $('<option selected="selected"></option>');
option.text(val);
option.val(key);
option.prop('selected', 'selected');
option.appendTo($('#cc_ccbundle_reference_UEB'));
non_selected_options[index++] = $(option);
});
var amount = non_selected_options.length;
if (amount > 1)
$.each(non_selected_options, function(key, val) {
if (amount - 1 === key)
val.attr('selected', false);
});
});
};
runUpdateUEBs();
$('#cc_ccbundle_reference_zone').bind({
change: runUpdateUEBs
});
}
And
//ReferenceController.php
//this is where "goalURL" goes
function updateUEBsAction() {
$id = $this->getRequest()->get('id');
$em = $this->getDoctrine()->getManager();
$uebs = $em->getRepository('CCBundle:UEB')->findBy(array('zone' => $id));
$ids_and_names = array();
foreach ($uebs as $u) {
$ids_and_names[$u->getId()] = $u->getName();
}
return new \Symfony\Component\HttpFoundation\Response(json_encode($ids_and_names));
}
With this I can load the UEBs corresponding the Zone being shown at the moment and every time a new Zone is selected alright, but only visually, not internally, hence:
the select populates fine but when I submit the form it doesn't go through with it and outputs "This value is not valid" on the UEB field and the
var_dump($form->get('UEB')->getData());
var_dump($form->get('UEB')->getNormData());
var_dump($form->get('UEB')->getViewData());
die();
from above outputs
null
null
string <the_value_of_the_option_tag> (length=1)
I need to know how to populate the select AND the internal data to be submitted too.
Thanks for bearing with this simple explanation.
I'm listening(reading).
Here is the answer I was looking for, it looks a lot like the one in the cookbook but somehow I understood this one better and I was able to apply it to my own problem, it only needed a few tweaks in the ajax call and the corresponding action, but only regarding my own problem.
thanks to all who cared to read my question and special thanks to Joshua Thijssen for his post.

How to add target to form in Symfony2

I am trying to add target to form.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('email', 'email', array('label' => 'Adres email'),'attr' => array('class' => 'class_name'))}
In controller I use:
$Register = new Register();
$form = $this->createForm(new RegisterType(), $Register);
$form -> handleRequest($Request);
just pasting some code i use, i defined the formType as service with tag "review" for my Review Entity, heres my controller action
$review = new Review();
$form = $this->createForm('review',$review);
$request = $this->getRequest();
// only handle request if form is submitted
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
$entity=$form->getData();
try {
$saved=$this->myService->saveReview($entity);
} catch (\Exception $e) {
$form->addError(new FormError($e->getMessage()));
return array(
"form"=>$form->createView()
);
}
return $this->redirect($this->generateUrl('some.url',array("some","mandatory-params")));
}
}
return array(
"form"=>$form->createView(),
);
http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

Categories