I am new to Twig. Can someone please show me how to pass in the selected option value of a select box so that it is selected when the ajax form is loaded?
What am I doing wrong?
warehouse_id = 32 in this example, and the form_widget automatically created my select list.
{{ form_widget(form.warehouse, {'selected': warehouse_id } ) }}
Thanks so much!
This was the easiest way that I found:
{{ form_widget(form.field, {value: 1 } ) }}
I think you don't need to do this. You can pass your entity (with data included) when form is created. Your dropdown will be with data selected.
See this code, for instance:
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('YourBundle:YourEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find entity.');
}
$editForm = $this->createForm(new YourFormType(), $entity);
//in entity goes with all data and your selectbox will be selected with correct data
return $this->render('YourBundle:YourController:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
));
or try to do this! Change 'selected' by 'value'
{{ form_widget(form.warehouse, {'value': warehouse_id } ) }}
Please, tell me about if you solved your doubt
Related
I'd like to know how can I put more than one form in one controller?
I did this, see the code below, in my controller which contains 2 forms; 1 to add a horse, and one to add a group of horses:
/*Add a horse*/
$cheval = new Chevaux();
$cheval->setParticulier($user->getParticulier());
$formAddHorse = $this->createFormBuilder($cheval)
->add('nom_cheval', TextType::class)
->add('save', SubmitType::class, array('label' => 'Ajouter'))
->getForm();
$formAddHorse->handleRequest($request);
if ($formAddHorse->isSubmitted() && $formAddHorse->isValid()) {
$cheval = $formAddHorse->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($cheval);
$em->flush();
return $this->redirectToRoute('app_acc');
}
/*add a group of horses*/
$team=new Team();
$team->setUser($user->getParticulier());
$formAddTeam = $this->createFormBuilder($team)
->add('profession', EntityType::class, array(
'class' => Profession::class,
'choice_label' => 'nom_prof',
'expanded' => true))
->add('save', SubmitType::class, array('label' => 'Nouvelle Team'))
->getForm();
$formAddTeam->handleRequest($request);
if ($formAddTeam->isSubmitted() && $formAddTeam->isValid()) {
$team = $formAddTeam->getData();
$em = $this->getDoctrine()->getManager();
/*
* Traitement des données
*/
return $this->redirectToRoute('app_acc');
}
and in the template :
<h2> -------Add a horse------ </h2>
{{ form_start(formHorse) }}
{{ form_widget(formHorse) }}
{{ form_end(formHorse) }}
<h2> ------------------------------ </h2>
<h2> -------Add team------ </h2>
{{ form_start(formTeam) }}
{{ form_widget(formTeam) }}
{{ form_end(formTeam) }}
<h2> ------------------------------ </h2>
However when I submit one of the forms, it seems that both are send. So it throws the error:
This form should not contain extra fields
in the form I didn't submit.
The data are send in the database properly, but the error is here and tells me that I am doing something wrong. How do I do to do this the right way?
I had a case like that once, here is what I did:
$form = $this->createForm(ProfileForm::class, $user);
$formPassword = $this->createForm(ChangePasswordForm::class, $user);
$form->handleRequest($request);
$formPassword->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
// My code to save some things...
}
}
if ($formPassword->isSubmitted()) {
if ($formPassword->isValid()) {
// My code to save some things...
}
}
It works for me but It seems like what you did, at first sight, though.
Maybe it's how you handle it in your template ?
You are looking for allow_extra_fields option which can be used like so.
$formBuilder = $this->createFormBuilder($team, array('allow_extra_fields' =>true))...
or like so for FormType class
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'allow_extra_fields' => true
)
);
}
This option allows you to submit some extra data, not specified in a form builder. As official documentation says
Usually, if you submit extra fields that aren't configured in your
form, you'll get a "This form should not contain extra fields."
validation error.
You can silence this validation error by enabling the
allow_extra_fields option on the form.
I am using dropdown menu to select the site as:
{{ Form::select('site', $sites, null, ['class' => 'form-control', 'placeholder' => 'Select a Site']) }}
{{ Form::label('site','site*') }}
I am storing the selected site in the database as site_id.
As this returns the index of the selected item from the list, so if the first item is selected the site_id would be stored as 0 in the database.
The problem here is, site_id is a foreign_key in my database and this is causing errors while matching it with the column:id of the sites table. As the id column generated by laravel migration scaffolding starts from 1 and the site_id returned by Form::select starts from 0.
Is there anyway that the index returned from Form::select would start from 1?
Or is there any other way to solve the problem?
When you're getting the sites from DB, keep original IDs to solve the problem:
$sites = Site::pluck('name', 'id');
This code will generate a list of sites' names with real IDs:
[1 => 'Site name 1', 2 => 'Site name 2']
You have many solutions
First, just verify with the validation, site must not be 0 since your controller
use Illuminate\Validation\Rule;
/** ... */
$this->validate($request, [
'site'=>['required',Rule::notIn([0])]
])
You can also check where you save Site model :
DB::transaction(function() use($request){
/** mapping of site attribute */
if($site->save())
{
}
}
You can also check since client side via JavaScript
{{ Form::select('site', $sites, null, ['id'=>'sites', 'class' => 'form-control', 'placeholder' => 'Select a Site']) }}
{{ Form::label('site','site*') }}
$("form input['type=submit']").click(function(e){
e.preventDefault();
if($('#sites').val() == 0)
{
alert('Please, select a site');
return;
}else{
$(this).submit();
}
})
if you want to inset name without id you can use $sites = Site::pluck('name', 'name'); I hope this will work.
I am looking for a method on how to possibly create a single dropdown for my form in symfony 2 that contains the value of the field 'abbr1' and 'abbr2' from a single record in table Params.
Lets say i have a single record in my table Params.
id: 1
title: sample
abbr1: qw12
abbr2: er34
Now i want to pick abbr1 and abbr2 as the value of a single dropdown. I have created a form but i dont know how to make both of them a choice. I can only pick them as a property one at a time. Here is my code:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'desiredAbbr',
'entity',
array(
'class' => 'FooBarBundle:Params',
'property' => 'abbr1',
//'property' => 'abbr2',
)
)
->add('save','submit',array('label'=>'Submit'))
;
}
Any Suggestions are much appreciated. Thanks a lot.
Update:
The expected dropdown value would look like this in html format:
{% for par in parameters %}
<select>
<option>{{param.abbr1}}</option> {# qw12 #}
<option>{{param.abbr2}}</option> {# er34 #}
</select>
{% endfor %}
ok, I missed that you want them as value, not as label. Then you should change you form like this
$choices = $options['abbrChoices'];
$builder->add('desiredAbbr', ChoiceType::class, array(
'choices' => $choices,
));
// in configureOptions method
$resolver->setDefaults(array(
'abbrChoices' => array(),
));
In controller where you create the form
$params = $this->getDoctrine()->getRepository('AppBundle:Params')->findAll();
$choices = array();
foreach ($params as $p) {
// key will be used as option value, value as option title
$choices[$p->getAbbr1()] = $p->getAbbr1();
$choices[$p->getAbbr2()] = $p->getAbbr2();
}
$form = $this->createForm(myform::class, array(), array('abbrChoices' => $choices));
BUT. How are you going to use this choice?
I'm new to Laravel and trying some stuff out. Hope you guys can point me in the right direction.
I have a form to add categories on a the page with the overview of all the categories. Now I'm routing to the same page when you want to add or edit a category. Problem is, I want the normal add form to show when the url is category/add and when the url is category/edit/id I want it to show the form to edit (with form model binding). I placed the code in an if else statement, but it always shows the edit form, therefore if I want to add a new category on the url categories I get an error because it's the edit form.
Here's the code in the index.bade.php:
#if(Request::url() === 'categories' )
{{ Form::open(array('url' => 'category/add', 'class' => 'form-horizontal')) }}
#else
{{ Form::model($category, array(
'url' => 'category/edit/'.$category->id ,
$category->id,
'class' => 'form-horizontal'))
}}
#endif
My controller:
public function index()
{
$categories = Category::get();
$category = new Category();
View::share('title', 'Mini Blog - Categories');
$view = View::make('category.index')->with('category', $category);
$view->categories = $categories;
return $view;
}
public function edit($id)
{
$categories = Category::get();
$category = Category::find($id);
View::share('title', 'Mini Blog - Edit category');
return View::make('category.index')->with(array('category' => $category, 'categories' => $categories));
}
Is this the way to go? Or is there a better way?
Instead of checking the URL I suggest you depend on the model variable. Ever Eloquent model has a property exists that tells you if the model has been loaded from the DB or it's a new instance.
#if( ! $category->exists)
{{ Form::open(array('url' => 'category/add', 'class' => 'form-horizontal')) }}
#else
{{ Form::model($category, array(
'url' => 'category/edit/'.$category->id ,
$category->id,
'class' => 'form-horizontal'))
}}
#endif
Actually you can use Form::model with an empty model as well, so you should be able to reduce it to this:
{{ Form::model($category, array(
'url' => ($category->exists ? 'category/edit/'.$category->id : 'category/add'),
'class' => 'form-horizontal'))
}}
There is a much better way.
In your controller do this:
public function create()
{
return View::make('create');
}
public function edit($id)
{
return View::make('edit')->withId($id);
}
Then in your views you have
Create.blade.php
{{ Form::open(array('url' => 'category/add', 'class' => 'form-horizontal')) }}
#include ('form')
{{ Form::close() }}
Edit.blade.php
{{ Form::model($category, array('url' => 'category/edit/'.$category->id, category->id, 'class' => 'form-horizontal')) }}
#include ('form')
{{ Form::close() }}
Form.blade.php
//Put your HTML form stuff here
everyone
I’am having trouble with empty dates and forms in Symfony2.
When I create an entity with an empty date, it works fine, a NULL value is inserted in the database. But when I want to edit it, it renders as today, I found no way of rendering the empy_values
As expected, “preferred_choices” does not work because “date” is not a “choice”.
Seems that a new \DateTime() is called somewhere.
Index and show actions have no problem:
[index/show.html.twig]
{% if entity.dueDate %}
{{ entity.dueDate|date('Y-m-d') }}
{% endif %}
If I ask in the controller, the behaviour is the expected one
[controller]
if (!$entity->getDueDate()) {
// enters here when there is NULL in the database
}
Here is the entity and form definitions:
[entity]
/**
* #var date $dueDate
*
* #ORM\Column(name="dueDate", type="date", nullable="true")
*/
private $dueDate;
[form]
$builder->add('dueDate', 'date', array('label'=>'Due date', 'empty_value' => array('year' => '----', 'month' => '----', 'day' => '----'),'required'=>false))
Please give me a hint, thank you in advance.
There is a related question from 2011-06-26 with no answer in google groups
https://groups.google.com/forum/#!msg/symfony2/nLUmjKzMRVk/9NlOB1Xl5RwJ
http://groups.google.com/group/symfony2/browse_thread/thread/9cb5268caccc4559/1ce5e555074ed9f4?lnk=gst&q=empty+date+#1ce5e555074ed9f4
With modern version of Symfony you seem to need:
$builder->add('dueDate', DateType::class, array(
'placeholder' => ['year' => '--', 'month' => '--', 'day' => '--']
)
empty_value has been replaced by placeholder and you need to pass an array with each "empty" value.
You can solve this way:
$builder->add('dueDate', 'date', array(
'label'=>'Due date',
'empty_value' => array('----'),
'required'=>false
))
You were close to the solution.
I did not want to render the form by myself, but as I was already doing that due to an unrelated issue, I developed some kind of fix:
[edit.html.twig]
<div class="entry {% if not entity.dueDate %}nullabledate{% endif %}">
{{ form_label(form.dueDate) }}
{{ form_errors(form.dueDate) }}
{{ form_widget(form.dueDate) }}
</div>
[add to some javascript file]
jQuery(document).ready(function() {
var nullDate = function(id) {
$(".nullabledate select").each(function(key,elem){
$(elem).val('');
})
}
nullDate();
}