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)
/* ... */
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
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).
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(),
));
}
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.
I'm just started working with Symfony2 and I have some problems with Pagination.
I have this code in my Account class:
public function indexAction($page)
{
$session = $this->get('session');
if ($session->get('valid')=='true') {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ProjectCRMBundle:Account')->findAll();
$user = new Account();
$form = $this->container->get('form.factory')->create(new AccountType());
$total = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->getQuery()->getResult();
/* total of résultat */
$total_users = count($total);
$users_per_page = 1;
$last_page = ceil($total_users / $users_per_page);
$previous_page = $page > 1 ? $page - 1 : 1;
$next_page = $page < $last_page ? $page + 1 : $last_page;
/* résultat à afficher*/
$entities = $this->getDoctrine()->getRepository('ProjectCRMBundle:Account')->createQueryBuilder('p')->setFirstResult(($page * $users_per_page) - $users_per_page)->setMaxResults(1)->getQuery()->getResult();
return $this->render('ProjectCRMBundle:Account:index.html.twig', array(
'entities' => $entities,
'last_page' => $last_page,
'previous_page' => $previous_page,
'current_page' => $page,
'next_page' => $next_page,
'total_users' => $total_users,
'form' => $form->createView(),
'user' => $user,
));
return $this->render('ProjectCRMBundle:Account:index.html.twig');
} else {
return $this->redirect($this->generateUrl('user_login'));
}
}
/**
* Creates a new Account entity.
*
*/
public function createAction(Request $request)
{
$entity = new Account();
$form = $this->createForm(new AccountType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('account_show', array('id' => $entity->getId())));
}
return $this->render('ProjectCRMBundle:Account:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
without forgetting the path on account.yml
account:
pattern: /{page}
defaults: { _controller: "ProjectCRMBundle:Account:index" , page: 1 }
At first look, it seems to work, but after trying to add a new account, I got this message:
LIMIT argument offset=-1 is not valid
Can anyone solve my problem?