I've got the following code to create a form in symfony2.
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('anne_stage_delete', array('id' => $id)))
->setMethod('DELETE')
->add('delete', 'submit')
->getForm()
;
}
But I can't find out how to add/change the name attribute. When I look in the rendered html the form name is form.
Make the form name in twig
<form action="{{ path('yourpath') }}" method="post" name="your_name-form">
{{ form_widget(form) }}
</form>
Or
You can use createNamedBuilder
$form = $this->get('form.factory')->createNamedBuilder('your-custom-name', 'form', null, array(
'constraints' => $collectionConstraint,
))
->add('delete', 'submit')
->getForm();
Related
I'm trying to make a form, which I self-defined the action like this in my controller:
$form = $this->createForm(ProgrammeSearchType::class, $search, [
'action' => $this->generateUrl('recherche_programme'),
'method' => 'GET',
]);
But, the form rendered in the view look like this:
<form id="myForm">
{{fields.....}}
</form>
So.. there is a problem. Why "action" is not specified in the HTML while I defined it into the controller.
Regards
Symfony doc: https://symfony.com/doc/current/forms.html#changing-the-action-and-http-method
Use {{ form_start(form) }} and {{ form_end(form) }} instead of <form> ... </form> tags in your view template.
I use a search form in Symfony 4.2.5, with GET method.
But the URL is not very... sexy.
I want to get a clean URL.
I have already disabled CSRF protection, and removed the submit from the FormBuilder ( otherwise, the submit button was ALSO on the URL).
The form :
public function searchForm()
{
//Form search creation
$form = $this->createFormBuilder(null, array('csrf_protection' => false))
->setAction($this->generateUrl('page'))
->setMethod('GET')
->add('object', TextType::class)
->getForm();
return $this->render('page.html.twig', ['searchForm' => $searchForm->createView()]);
}
The view :
<form class="search">
{{ form_start(searchForm) }}
{{ form_row(searchForm.object, {'attr' : {'placeholder': "Search..."}}) }}
<button id="searchSubmit" class="btn btn-success">Search </button>
{{ form_end(searchForm) }}
</form>
With this code, I get localhost/page?form[object]=SearchTerm
I know, it is a detail, but I want to get an URL like localhost/page?object=SearchTerm.
I have started to study Symfony2 since I will probably need in my work.
routing.yml:
account_register:
path: /register
defaults: {_controller: AppBundle:Register:index}
RegisterController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\User;
class RegisterController extends Controller
{
/**
* #Route("/register")
*/
public function indexAction(Request $request)
{
$register = new User();
$form = $this->createFormBuilder($register)
->add('email', 'email', array('required' => false))
->add('password', 'password', array('required' => false))
->add('alias', 'text', array('required' => false))
->add('register', 'submit', array('label' => 'Register'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
$em = $this->getDoctrine()->getManager();
$em->persist($register);
$em->flush();
exit("Error");
//return $this->redirectToRoute('task_success');
}
return $this->render('pages/register.html.twig', array(
'form' => $form->createView(),
));
}
}
regiser.html.twig:
{% extends 'base.html.twig' %}
{% block body %}
<br /><br />
<div class = "window">
<form>
<br /><br /><br /><br /><br /><br /><br />
{{ form_start(form) }}
{{ form_errors(form) }}
<div id=center-text>Email</div>
<div class="textfield" id=center> {{ form_widget(form.email, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Password</div>
<div class="textfield" id=center> {{ form_widget(form.password, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }} </div>
<br />
<div id=center-text>Alias</div>
<div class="textfield" id=center> {{ form_widget(form.alias, {'attr': {'class': 'textfield', 'size': '22', 'maxlength': '100'}}) }}</div>
<br /><br />
<br />
<center>
{{ form_widget(form.register, {'attr': {'class': 'button'}}) }}
</center>
{{ form_end(form) }}
</form>
{% endblock %}
When i press the submit button only the url changes from http://localhost/website/web/app_dev.php/register
to
http://localhost/website/web/app_dev.php/register?form%5Bemail%5D=&form%5Bpassword%5D=&form%5Balias%5D=&form%5Bregister%5D=&form%5B_token%5D=hd70y_KjUEY8v51dQjnjU0ZMTJ0BYOihurV6IcIvghY
What is happening is the expected form's flow. The form that you are submitting is redirecting to the same page.
If you don't want your form to be in GET, you can change it for POST :
$form = $this->createFormBuilder($register)
->setMethod('POST')
->...
When you are redirected after submitting the form, $form->handleRequest($request) binds the request (your data submitted) with the form that is just created. $form->isValid() then checks if your data is valid according to your form.
If you don't see any change after being redirected, you should check if $form->isValid() returns true.
If you want to redirect your form to another controller method, you should create another resource and then set the action attribute of your form thanks to the setAction() method.
To sum up, everything that I just told you is written and explained on this page, and you definitely should read it ! :-).
Silly me, the html was my test code and then i added the symfony {{ blocks }} and forgot to remove the old tags
Using Symfony2.3.4.
I'm trying to create a form without using a type, it is actually a very small form, only two selects loading their options from the database, so far it works, what I can not do is to get the form data(in the controller) when it is submitted. I tried to follow the instruction here but I can't get it right.
Here is my code so far:
Controller:
function to pass the data to the form:
public function selectAction($id, $id_actpost){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ActPostBundle:Edition')->find($id);
$students = $em->getRepository('PersonBundle:Students')->findAll();
$students2 = $em->getRepository('PersonBundle:ForeignStudents')->findAll();
if (!$entity) {
throw $this->createNotFoundException('Unable to find Edicion entity.');
}
return $this->render('ActPostBundle:Edition:select.html.twig', array(
'entity' => $entity,
'id_actpost' => $id_actpost,
'students' => $students,
'foreignstudents' => $students2,
));
}
html fragment regarding the form itself:
<form class="form-horizontal sf_admin_form_area"
action="{{ path('edition_update_selected',
{ 'id': entity.id, 'id_actpost': id_actpost }) }}"
method="post" enctype="multipart/form-data">
<div style="margin-left: 80px" class="row-fluid">
<div class="span12">
<select name="students" multiple="multiple">
{% for s in students %}
<option {%if s in entity.students%}selected="selected"{%endif%}>
{{s}}</option>
{%endfor%}
</select>
</div>
</div>
<div class="row-fluid">
<select name="students2" multiple="multiple">
{% for s in students2 %}
<option {%if s in entity.foreignstudents%}selected="selected"
{%endif%}>{{s}}</option>
{%endfor%}
</select>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
<i class="glyphicon-refresh"></i> {{'Update' | trans}}</button>
<a class="btn" href="{{ path('edition', {'id_actpost' : id_actpost }) }}">
<i class="glyphicon-ban-circle"></i> {{'Cancel' | trans }}
</a>
</div>
</form>
and here is what I read from the link posted at the beginning:
function to get the submitted data and update the database, although the database part can stay ignored until I manage to get the data from the form:
public function update_selectedAction(Request $request, $id, $id_actpost) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ActPostBundle:Edition')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Edicion entity.');
}
$defaultData = array('message' => 'Type here');
$editForm = $this->createFormBuilder($defaultData)
->add('students','choice')
->add('students2', 'choice')
->getForm();
$editForm->handleRequest($request);
I would like to know if what I read is actually what I need, because although I think it is I might be wrong, so any insights regarding this matter or even any other way to do it will be really appreciated.
You should use symfony's form builder to build the form in your update_selectedAction() like
public function update_selectedAction(Request $request, $id, $id_actpost)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ActPostBundle:Edition')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Edicion entity.');
}
$defaultData = array('message' => 'Type here');
$form = $this->createFormBuilder($defaultData)
->add('students', 'entity',array('class' => 'PersonBundle:Students',
'property' => 'students','expanded'=>false,'multiple'=>false))
->add('students2', 'entity',array('class' => 'PersonBundle:ForeignStudents',
'property' => 'foreignstudents','expanded'=>false,'multiple'=>false))
->add('submit','submit')
->getForm();
if ($request->getMethod() == "POST") {
$form->submit($request);
if ($form->isValid()) {
$postData = current($request->request->all());
var_dump($postData); /* All post data is here */
/* echo $postData['students']; */
/* echo $postData['students2']; */
/*
* do you update stuff here
* */
}
}
return $this->render('ActPostBundle:Edition:select.html.twig', array('form'=>$form->createView()));
}
In your twig i.e ActPostBundle:Edition:select.html.twig render your form
{{ form(form) }}
Edit from comments
In your twig file render your form like
{{ form_errors(form) }}
{{ form_row(form.students) }}
{{ form_row(form.students2) }}
{{ form_row (form._token) }}
<input type="submit"> /* your submit button */
Edit from comments 2
IF you want to put the text in value attribute of selectbox you can use choice field type
$students = $em->getRepository('PersonBundle:Students')->findAll();
$students2 = $em->getRepository('PersonBundle:ForeignStudents')->findAll();
$studentsArray=array();
$students2Array=array();
foreach($students as $s){
$studentsArray[$s->getStudents()]=$s->getStudents();
}
foreach($students2 as $s){
$students2Array[$s->getForeignstudents()]=$s->getForeignstudents();
/* here array key part will be the value of selectbox like $students2Array['your val to get in post data'] */
}
$form = $this->createFormBuilder($defaultData)
->add('students', 'choice',array('choices' => $studentsArray,'expanded'=>false,'multiple'=>false))
->add('students2', 'choice',array('choices' => $students2Array,'expanded'=>false,'multiple'=>false))
->add('submit','submit')
->getForm();
I have an entity "group", with a name and a description.
I created a form for update both, but when I click on submit, values are set to NULL.
I also tried to create a new entity. But in this case, their value are set to default value in the field.
Here's my code :
my form :
<form method="post" class="form-signin" {{ form_enctype(form) }}>
<input id="name" name="form[name]" required="required" value="{{ group.name }}"></input>
<textarea id="description" name="form[description]" >{{ group.description }}</textarea>
<input class="btn btn-lg btn-primary btn-block" type="submit" id="_submit" name="_submit" value="submit" />
</form>
my controller :
public function updateParametersAction()
{
$user = $this->get('security.context')->getToken()->getUser();
$repository = $this->getDoctrine()
->getManager()
->getRepository('MyBundle:Groups');
$group = $repository->findOneByIdUser($user->getId());
$form = $this->createFormBuilder($group)
->add('name', 'text')
->add('description', 'textarea')
->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$em = $this->getDoctrine()->getManager();
$em->persist($group);
$em->flush();
}
return $this->render('MyBundle:Client:updateParameters.html.twig', array(
'group' => $group,
'form' => $form->createView()
));
}
What's wrong ?
You have to bind a request to the form:
// (...)
$form = $this->createFormBuilder($group)
->add('name', 'text')
->add('description', 'textarea')
->getForm();
$form->handleRequest($request);
// (...)