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(),
));
}
Related
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
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.
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)
/* ... */
I have an entity called Objective and its property called 'weight' and I can edit one objective at a time.. and now i want to edit all weights in a single form and persist them in DB using Doctrine..
This issue helped me in bringing all objective weights on a single form..
Edit multiple entities in one form
Now I am trickling around on how to save all weight values from the form in DB with a single click of save button..
Below is my code so far..
This is the controller action:-
/**
* #Route("/mou/objectives/manage", name="objective_manage")
*/
public function manageAction(Request $request){
$objs = $this->getDoctrine()
->getRepository('AppBundle:Objective')
->findAll();
$form = $this->createFormBuilder()
->add('weight', 'collection', array(
'type' => new WeightType() ,
'allow_add' => false,
'allow_delete' => false,
'label' => false))
->add('save', 'submit')
->getForm();
$form->setData(array('weight' => $objs));
/* Till here things are fine */
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
/* **Here I need help how to persist all weight values.. maybe inside a loop.. hence This is the missing piece** */
foreach($objs as $obj){
$obj =new Objective();
$obj = $em->getRepository('AppBundle:Objective')->find($obj);
$obj->setWeight($obj);
$em->persist($obj);
}
$em->flush();
return $this->redirectToRoute('objective_manage');
}
return $this->render('keyobjective/manage.html.twig', array(
'objs' => $objs,
'form' => $form->createView()
));
}
This is the FormType:-
class WeightType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('weight','text', array('label' => false));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Objective'
//'data_class' => null
));
}
/**
* #return string
*/
public function getName()
{
return 'appbundle_objective';
}
}
and this is twig template:-
{% extends 'base.html.twig' %}
{% block body %}
{{form_start(form)}}
{{form_label(form.weight,'Enter Weight')}}
{{form_widget(form.weight)}}
{{form_end(form)}}
{% endblock %}
Any suggested approach..!!
Somehow I figured this out.. after form handle request I created a loop to iterate through the number of objectives being edited and then inside of it another foreach loop which transforms the weight values received from the Form to the setWeight() method one by one:-
/**
* #Route("/mou/objectives/manage", name="objective_manage")
*/
public function manageAction(Request $request){
$objs = $this->getDoctrine()
->getRepository('AppBundle:Objective')
->findAll();
$count = count($objs);
for($i =0; $i < $count; $i++){
$objsarray = new Objective();
}
$form = $this->createFormBuilder()
->add('weight', 'collection', array(
'type' => new WeightType() ,
'allow_add' => false,
'allow_delete' => false,
'options' => array('label' => false),
))
->add('save', 'submit')
->getForm();
$form->setData(array('weight' => $objs));
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em = $this->getDoctrine()->getManager();
for($i=0; $i < count($objs); $i++){
$obj = new Objective();
$obj = $em->getRepository('AppBundle:Objective')->find($objs[$i]);
$weight = $form->get('weight')->get($i)->getData();
foreach($weight as $val){
$obj->setWeight($val);
$em->persist($obj);
}
}
$em->flush();
$this->addFlash(
'notice',
'Objective weight updated'
);
return $this->redirectToRoute('objective_manage');
}
return $this->render('keyobjective/manage.html.twig', array(
'objs' => $objs,
'form' => $form->createView()
));
}
I have an application which only admin can create users and I use FOSUserBundle.
I can create user but I've got some problems when I want to login the created user.
They can't login.
I use the default login from FOSUserBundle and it works with users created from command line.
What I missed to do?
This is my createAction from my UserController:
public function createAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
$this->get('session')->getFlashBag()->add('success', 'The user has been added!');
return $this->redirect($this->generateUrl('crm_users'));
}
return $this->render('LanCrmBundle:User:create.html.twig', array(
'form' => $form->createView(),
));
}
This is my buildForm:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('email')
->add('enabled')
->add('password')
->add('roles', 'choice', array('choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'),'multiple' => true));
}
You are not encrypting the password while creating the user.
Change the code inside form valid success to,
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$userManager = $this->container->get('fos_user.user_manager');
$user->setPlainPassword($user->getPassword());
$userManager->updatePassword($user);
$em->persist($user);
$em->flush();
}
Maybe your default enabled value is false.
Try to set it directly :
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user->setEnabled(true);
$em->persist($user);
$em->flush();
}
Or put it in your default value in entity class.