Embed form and choice list - php

I have a form, SiteType, with an other form, DomainType, embbed. But when I tried to display in the site form the domain name field, which is a choice list, it appears 3 times (each list contains all the domains in the DB) instead of one time.
This is my SiteType :
class SiteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'label' => 'Nom du site',
'required' => true
))
->add('nameBundle', 'text', array(
'label' => 'Nom du bundle du site',
'required' => true
))
->add('numClient', 'integer', array(
'label' => 'Numéro client du site',
'required' => true
))
->add('domains', 'collection', array(
'type' => new DomainType(),
));
}
...
}
and my DomainType:
class DomainType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('domainName','entity', array(
'class' => 'EliophotBackBundle:Domain',
'property' => 'domainName',
'label' => 'Nom du domaine'
));
}
...
}
and the form where I display the form :
<form action="{{ path('site_create') }}" method="post">
{{ form_row(form.name) }}
{{ form_row(form.nameBundle) }}
{{ form_row(form.numClient) }}
{% for domain in form.domains %}
{{ form_row(domain.domainName) }}
{% endfor %}
{{ form_rest(form) }}
<div class="btn-group">
<button type="submit" class="btn btn-success">Ajouter</button>
</div>
</form>
My SiteController :
public function newSiteAction()
{
$site = new Site();
$repository = $this->get('doctrine')
->getRepository('TestBackBundle:Domain');
$domains = $repository->findAll();
foreach($domains as $domain) {
$domainObject = new Domain();
$domainObject->setDomainName($domain->getDomainName());
$site->getDomains()->add($domainObject);
}
$newForm = $this->createForm(new SiteType(), $site);
return $this->render('TestBackBundle:Site:new_site.html.twig', array(
'site' => $site,
'form' => $newForm->createView(),
));
}
I would like to diplay only one choice list with all the domains name... How can I do this ?

I think you can resolve this like this:
SiteType
$builder
->add('name', 'text', array(
'label' => 'Nom du site',
'required' => true
))
->add('nameBundle', 'text', array(
'label' => 'Nom du bundle du site',
'required' => true
))
->add('numClient', 'integer', array(
'label' => 'Numéro client du site',
'required' => true
))
->add('domains','entity', array(
'class' => 'EliophotBackBundle:Domain',
'property' => 'domainName',
'label' => 'Nom du domaine',
'multiple' => true
));
In this case you wouldn't have need for DomainType. As for the controller can you clarify this snippet:
$domains = $repository->findAll();
foreach($domains as $domain) {
$domainObject = new Domain();
$domainObject->setDomainName($domain->getDomainName());
$site->getDomains()->add($domainObject);
}
Why are you fetching and then reconstructing all the domains? Are the domains from Site entityt not of type TestBackBundle:Domain? If they are in fact, you could just:
$domains = $repository->findAll();
$site->setDomains(new ArrayCollection($domains)); // don't forget sto `use` ArrayCollection
Hope this helps a bit...

Related

Symfony 4 : Error creating an add entity form (object not found by the #ParamConverter annotation)

I'm trying to make a form to add an entity in my database (a project). I realized exactly the same thing for other entities, everything works, but for this one (a project), it does not work ...
Screen of error : http://image.noelshack.com/fichiers/2019/02/1/1546884788-capture.png
ProjectController :
/**
* #Route("/projects/add", name="add_projects")
*/
public function addProject(Request $request)
{
$em = $this->getDoctrine()->getManager();
$project = new Project();
$form = $this->createForm(AddProjectType::class, $project);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($project);
$em->flush();
return $this->redirectToRoute('index_projects');
}
return $this->render('/project/add.html.twig', [
'form' => $form->createView(),
]);
}
AddProjectType :
class AddProjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, array(
'attr' => array(
'placeholder' => 'Nom',
),
'label' => false,
))
->add('price', IntegerType::class, array(
'attr' => array(
'placeholder' => 'Prix',
),
'label' => false,
))
->add('type', ChoiceType::class, array(
'choices' => array(
'Application web' => 'Application web',
'Site internet' => 'Site internet',
'Application mobile' => 'Application mobile',
'Autre' => 'Autre',
),
'label' => false,
))
->add('client', EntityType::class, array(
'class' => User::class,
'choice_label' => function($user) {
return $user->getUsername();
},
'label' => false,
))
->add('state', ChoiceType::class, array(
'choices' => array(
'A faire' => 'A faire',
'En cours' => 'En cours',
'Terminé' => 'Terminé',
),
'label' => false,
))
->add('description', TextareaType::class, array(
'attr' => array(
'placeholder' => 'Description',
),
'label' => false,
))
->add('Ajouter', SubmitType::class, [
'attr' => [
'class' => 'btn btn-success',
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Project::class,
]);
}
}
add.html.twig :
{% extends "./base.html.twig" %}
{% block title %}{{ parent() }}Ajouter un projet{% endblock %}
{% block stylesheets %}
{{ parent() }}
<style>
form input, form select, form textarea {
width: 100%;
margin: .5em 0;
}
</style>
{% endblock %}
{% block body %}
{{ parent() }}
<h1 class="title-page">Ajouter un projet</h1>
<div class="container-fluid">
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
{% endblock %}
Did you look into the database whether the project is added?
In your controller I don't see a reason for a ParamConverter, therefore I guess that the error happens after the redirect to index_projects
I just managed to find out why I had this error, I'll post the salution here so that other people have it:
I had in this controller a route /projects/{id} (to access the details of a project), I modified it by /projects/details/{id}

Variable "url_resources" does not exist. Here I'm trying to display the values of form that i just entered above

enter image description hereVariable "url_resources" does not exist. Here I'm trying to display the values of form that i just entered above. It always fetches me the same error. I want it to be displayed on the same page without getting navigated to a different one. i have created 3 textboxes for displaying the appropriate fiels as you can see in the twig code.
Controller
<?php
namespace UrlResourceBundle\Controller;
use UrlResourceBundle\Entity\url_resources;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class DefaultController extends Controller
{
/**
* #Route("/", name="todo_list")
*/
public function listAction()
{
$urls_resources = $this->getDoctrine()
->getRepository('UrlResourceBundle:url_resources')
->findAll();
return $this->render('todo/index.html.twig', array(
'urls_resources' => $urls_resources
));
}
/**
* #Route("/todo/create", name="todo_create")
*/
public function createAction(Request $request)
{
$url_resources = new url_resources;
$form = $this->createFormBuilder($url_resources)
->add('title', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('url', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('description', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('save', SubmitType::class, array('label' => "Create",'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
//Get Data
$title = $form['title']->getData();
$url = $form['url']->getData();
$description = $form['description']->getData();
$url_resources->setTitle($title);
$url_resources->setUrl($url);
$url_resources->setDescription($description);
$em = $this->getDoctrine()->getManager();
$em->persist($url_resources);
$em->flush();
$this->addFlash(
'notice',
'Entry Created'
);
return $this->redirectToRoute('todo_create');
return $this->redirect($request->getUri());
}
return $this->render('todo/create.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/todo/edit/{id}", name="todo_edit")
*/
public function editAction($id, Request $request)
{
$url_resources = $this->getDoctrine()
->getRepository('UrlResourceBundle:url_resources')
->find($id);
$url_resources->setTitle($url_resources->getTitle());
$url_resources->setUrl($url_resources->getUrl());
$url_resources->setDescription($url_resources->getDescription());
$form = $this->createFormBuilder($url_resources)
->add('title', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('url', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('description', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('save', SubmitType::class, array('label' => "Update",'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
//Get Data
$title = $form['title']->getData();
$url = $form['url']->getData();
$description = $form['description']->getData();
$em = $this->getDoctrine()->getManager();
$url_resources = $em->getRepository('UrlResourceBundle:url_resources')->find($id);
$url_resources->setTitle($title);
$url_resources->setUrl($url);
$url_resources->setDescription($description);
$em->flush();
$this->addFlash(
'notice',
'Entry Updated'
);
return $this->redirectToRoute('todo_list');
}
return $this->render('todo/edit.html.twig', array(
'url_resources' => $url_resources,
'form' => $form->createView()
));
}
/**
* #Route("/todo/details/{id}", name="todo_details")
*/
public function detailsAction($id)
{
$url_resources = $this->getDoctrine()
->getRepository('UrlResourceBundle:url_resources')
->find($id);
return $this->render('todo/details.html.twig', array(
'url_resources' => $url_resources
));
}
/**
* #Route("/todo/delete/{id}", name="todo_delete")
*/
public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();
$url_resources = $em->getRepository('UrlResourceBundle:url_resources')->find($id);
$em->remove($url_resources);
$em->flush();
$this->addFlash(
'notice',
'Entry deleted');
return $this->redirectToRoute('todo_list');
}
}
Twig
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header">Create</h2>
{{form_start(form)}}
{{form_widget(form)}}
<ul class="list-group">
<li class="list-group-item">Title: {{url_resources.title}}</li>
<li class="list-group-item">URL: {{url_resources.url}}</li>
<li class="list-group-item">Description: {{url_resources.description}}</li>
</ul>
{{form_end(form)}}
{% endblock %}
Of course it s undefine, because you don't passe it,
pass it to your render
return $this->render('todo/create.html.twig', array(
'form' => $form->createView(),
'url_resources' => $your variable name
));

Symfony, Keep Get Argumments in Search form after submit

Hi,
i have created a search form using GET method, to my indexAction, the form contains virtual fields.
i created the logic for searching inside the indexAction.
My problem is when i submit the form, all inputs values become empty.
What i want is to keep the values passed as arguments in form inputs
here is my FormType :
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class, array(
'required' => false,
'attr' => array(
'placeholder' => 'Chercher',
)
))
->add('client', EntityType::class, array(
'required' => false,
'class' => 'AppBundle:Person',
'placeholder' => 'Choisir client',
'attr' => array(
'class' => 'select2',
)
))
->add('date_start', DateTimeType::class, array(
'required' => false,
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'inherit_data' => true,
'attr' => array(
'name' => 'date_start',
'class' => 'datepicker',
'placeholder' => 'Date début',
'value' => ''
)
))
->add('date_end', DateTimeType::class, array(
'required' => false,
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'inherit_data' => true,
'attr' => array(
'name' => 'date_end',
'class' => 'datepicker',
'placeholder' => 'Date fin',
'value' => ''
)
))
;
}
The indexAction :
public function indexAction(Request $request)
{
$getArgs = $request->query->get('order');
dump($getArgs);
$form = $this->createForm('AppBundle\Form\Search\OrderType', new Order(), array('get' => $getArgs));
$form->handleRequest($request);
$repo = $this->getDoctrine()->getRepository('AppBundle:Order');
$query = $getArgs ? $repo->findAllMatched($q) : $repo->createQueryBuilder('o');
$paginator = $this->get('knp_paginator');
$orders = $paginator->paginate($query);
return $this->render('AppBundle:Order:index.html.twig', array(
'orders' => $orders,
'form' => $form->createView(),
));
}
Any suggestions are wellcome.
For now, i resolved the problem in this way :
<div class="nav box-search">
<form method="GET" class="form-inline">
<div class="pull-right">
<button type="submit" class="btn btn-default">{{ 'actions.search' | trans }}</button>
</div>
<div class="pull-left">
{% set params = app.request.query.all %}
{{- form_widget(form.title, { 'attr': {'value': params.order.title| default('')} }) -}}
{{ form_widget(form.client, {value: params.order.client| default('') }) }}
{{- form_widget(form.date_start, { 'attr': {'value': params.order.date_start| default('')} }) -}}
<i class="fa fa-exchange"></i>
{{- form_row(form.date_end, { 'attr': {'value': params.order.date_end| default('')} }) -}}
</div>
</form>
</div>
It's not that bad solution, but what i would is to have this parameters configuration in the FormType.

Symfony3 The controller must return a response (null given)

I have this issue here with Symfony3. I am pretty new at this so I have no idea where to debug.
UserController.php
public function userEdit($id, Request $request)
{
$user = $this->getDoctrine()
->getRepository('AppBundle:Users')
->find($id);
$user->setEmail($user->getEmail());
$user->setPassword($user->getPassword());
$user->setPhone($user->getPhone());
$user->setType($user->getType());
$user->setName($user->getName());
$user->setFeedback($user->getFeedback());
$user->setPicture($user->getPicture());
$user->setRating($user->getRating());
$user->setInfo($user->getInfo());
$user->setDatecreated($user->getDatecreated());
$form = $this->createFormBuilder($user)
->add('email', EmailType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('password', RepeatedType::class, array(
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'options' => array('attr' => array('class' => 'password-field form-control', 'style' => 'margin-bottom:15px')),
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
))
->add('phone', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('type', ChoiceType::class, array('choices' => array('Client' => 'Client', 'Builder' => 'Builder'), 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('picture', FileType::class, array('data_class' => null,'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('info', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('save', SubmitType::class, array('label' => 'Register', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Get Data
$email = $form['email']->getData();
$password = $form['password']->getData();
$phone = $form['phone']->getData();
$type = $form['type']->getData();
$name = $form['name']->getData();
$picture = $form['picture']->getData();
$info = $form['info']->getData();
$now = new\DateTime('now');
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:Users')->find($id);
$user->setEmail($email);
$user->setPassword($password);
$user->setPhone($phone);
$user->setType($type);
$user->setName($name);
$user->setFeedback($user->getFeedback());
$user->setPicture($picture);
$user->setRating($user->getRating());
$user->setInfo($info);
$user->setDatecreated($now);
$images = base64_encode(stream_get_contents($user->getPicture()));
$em->flush();
$this->addFlash(
'notice',
'User Updated'
);
return $this->render('home/useredit.html.twig', array(
'user' => $user,
'form' => $form->createView(),
'images' => $images,
));
}
}
At first i was getting this error :
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) resource. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) resource to an instance of Symfony\Component\HttpFoundation\File\File.
Then i read some posts here and I added 'data_class' => null, where the FileType::class is added to the form.
And from then on I get this error:
The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?
This is the file that i`m rendering the form to:
useredit.html.twig
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header">EDIT USER {{ user.name }}</h2>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
{% endblock %}
Ideas?
What if the form is not submitted? You don't return anything, just as the error states.
You could move your return $this->render at the end below the next } so that this is called whether a form is submitted or not.
Or do something custom:
if ($form->isSubmitted() && $form->isValid()) {
....
} else {
// Return something if the form is not submitted
}
The problem is that this condition if ($form->isSubmitted() && $form->isValid()) { is resulting in false and for that reason nothing is returning.
Hope this help you.
You return your twig template only if your form is submitted and valid...
You put your return statement inside if ($form->isSubmitted() && $form->isValid()) { } condition, so method returns null.
return $helpers->json(array(
"status" => "error",
"data" => "Send json with post !!"
));

Symfony2 nothing happens when I display my form inside a class

So I am following the documentation and I am making a form inside its own class:
<?php
namespace Mp\ShopBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
class RegisterFormType extends AbstractType
{
public function registerForm(FormBuilderInterface $builder, array $options) {
$builder
>add('title', 'choice', array(
'choices' => array('-' => '-', 'mr' => 'Mr.', 'mrs' => 'Mrs.', 'mss' => 'Miss.'),
'label' => 'Title * ',
'attr' => array('class' => 'span1')))
->add('firstName', 'text', array(
'label' => 'First Name * ',
'attr' => array('placeholder' => 'First Name')))
->add('lastName', 'text', array(
'label' => 'Last Name * ',
'attr' => array('placeholder' => 'Last Name')))
->add('Email', 'email', array(
'label' => 'Email * ',
'attr' => array('placeholder' => 'Email')))
->add('Password', 'password', array(
'label' => 'Password * ',
'attr' => array('placeholder' => 'Password')))
->add('DateOfBirth', 'date', array(
'label' => 'Date Of Birth * ',
'widget' => 'choice'))
->add('Company', 'text', array(
'label' => 'Company ',
'attr' => array('placeholder' => 'Company')))
->add('Adress', 'text', array(
'label' => 'Adress * ',
'attr' => array('placeholder' => 'Adress')))
->add('Country', 'country', array(
'label' => 'Country * ',
'attr' => array('placeholder' => 'Country')))
->add('State', 'text', array(
'label' => 'State * ',
'attr' => array('placeholder' => 'State')))
->add('City', 'text', array(
'label' => 'City * ',
'attr' => array('placeholder' => 'City')))
->add('ZipPostalCode', 'text', array(
'label' => 'Zip / Postal Code *',
'attr' => array('placeholder' => 'Zip / Postal Code')))
->add('AdditionalInformation', 'textarea', array(
'label' => 'Additional Information ',
'attr' => array('placeholder' => 'Additional Information')))
->add('HomePhone', 'number', array(
'label' => 'Home phone ',
'attr' => array('placeholder' => 'Home Phone')))
->add('MobilePhone', 'number', array(
'label' => 'Mobile phone ',
'attr' => array('placeholder' => 'Mobile Phone')))
->add('save', 'submit', array('label' => 'Register'));
}
public function getName()
{
return 'register_form_users';
}
}
It looks like a simple form. Now in my controller I want to show it:
use Mp\ShopBundle\Form\Type\RegisterFormType;
public function registerAction()
{
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('MpShopBundle:Product')->findAll();
$form = $this->createForm(new RegisterFormType());
return $this->render('MpShopBundle:Frontend:registration.html.twig', array(
'products'=>$products,
'form'=>$form->createView(),
));
}
My twig:
<h3>Your personal information</h3>
{{ dump(form) }}
{% form_theme form _self %}
{{ form(form) }}
The thing is im not getting my form. The page and the template loads fine, but not my form.
When I do {{ dump(form) }} I get something:
FormView {#2110 ▼
+vars: array:33 [▶]
+parent: null
+children: array:1 [▶]
-rendered: true
}
As you can see I am getting the form? But it is not displaying?... Why is that?
You must change your method
public function registerForm(FormBuilderInterface $builder, array $options) {
to
public function buildForm(FormBuilderInterface $builder, array $options)

Categories