Setting the value attribute in a dropdown menu Symfony2 - php

I'm fairly new to Symfony2 and am working with the form builder trying to create a dropdown menu from the database. I can populate the dropdown without problem but each options value attribute just gets set to a number when it needs to be set to either the options text or no value attribute but I can't find anything in the documentation about setting the value.
$builder->add('institution', 'entity', array(
enter code here 'class' => 'JacksonFramesStoreBundle:Institution',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('i')
->where('i.type = :type')
->setParameter('type', 'University');
},
'empty_value' => 'Select:',
'empty_data' => null,
));
This outputs:
<select id="selectUniversity" name="selectUniversity">
<option value="0"></option>
<option value="1">Australian Catholic University</option>
<option value="2">Australian National University</option>
<option value="3">Bond University</option>
</select>
EDIT - this is the relevant section of the twig
<!-- University Panel -->
<div id="uniPanel" style="display:none;">
<p>{{ form_label(form.institution) }}<br />
<span class="inputLine">
{{ form_errors(form.institution) }}
{{ form_widget(form.institution) }}
</span>
</p>
</div>

In the controller, after if ($form->isValid()), try using:
$value = ($entity->getInstitution()) ? $entity->getInstitution()->getId() : null);
I don't really know if I really understood your question

Related

Fom::select in laravel empty for default

I´m trying to create a form select in laravel.
I was created perfectly, but in my view first option is 0 and one first option empty
I need to remove this 0 and option empty, but i don't know how i can do it, this is my actual code:
<div class="form-group row ">
{!! Form::label('restaurant_id', trans("lang.blog_restaurant_id"),['class' => 'col-3 control-label text-right']) !!}
<div class="col-9">
{!! Form::select('restaurant_id', [null => null, $restaurant], null, ['class' => 'select2 form-control']) !!}
<div class="form-text text-muted">{{ trans("lang.blog_restaurant_id_help") }}</div>
</div>
</div>
$restaurant it's one data array for to fill my select. I read that with first option null put selected option empty, but generate a empty option and 0.
Thanks for help me.
UPDATE
Laravel include optgroup into Form::select that it´s triggering my 0 this it´s the problem. i need delete optgroup
<select class="select2 form-control select2-hidden-accessible" id="restaurant_id" name="restaurant_id" tabindex="-1" aria-hidden="true">
<option value="" selected="selected"></option>
<optgroup label="0">
<option value="17">Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf</option>
<option value="28">restaurante de pruebas</option>
<option value="29">probando</option>
<option value="30">pincho de castilla2</option>
</optgroup>
update 2
getting list of restaurant:
$restaurant = $this->restaurantRepository->pluck('name', 'id');
this is result in blade:
{"17":"Foody Lindgren, Cremin and Erdman gdfgfg fgfg fg fgfg g fggf","28":"restaurante de pruebas","29":"probando","30":"pincho de castilla2"}
Add toArray():
$restaurant = $this->restaurantRepository->pluck('name', 'id');
$restaurant->toArray();
same result
Please try this. Add blank key and blank value like below.
{!! Form::select('restaurant_id', ["" => "", $restaurant], null, ['class' => 'select2 form-control']) !!}
It seems that the $restaurant is an array.
So, you'd better do something like this:
Form::select('restaurant_id', $restaurant, null, ['class' => 'select2 form-control'])
you may need a proper mapping for your $restaurant in your controller, depending on what you need, like adding an empty option in the beginning.
// in Controller
$options = ["" => "select"] + $restaurant;
// In view
Form::select('restaurant_id', $options, null, ['class' => 'select2 form-control'])
update 2
You should make sure to send the $restaurant as an array:
$restaurant = $this->restaurantRepository->pluck('name', 'id')->toArray();
For adding an empty option:
$restaurant = ["" => "select"] + $restaurant;
There is also another option:
You can even add the select box manually instead of using Form::select.
<select class="select2 form-control" id="restaurant_id" name="restaurant_id">
<option value="" selected="selected"></option>
#foreach($restaurant as $value => $option)
<option value="{{ $value }}">{{ $option }}</option>
#endforeach
</select>

Getting 'old' value of a select input laravel

I'm working on validating my registration form.
If the input is a regular input, i can populate the previous value if it fails like so
<input type="tel" name="phone" value="{{old('phone')}}">
How do I populate the value on a select option?
<div class="input--select">
<label>Age Range <span>*</span></label>
<select name="age_range" class="age-range" value="{{old('age_range')}}" required>
<option selected disabled>Select your age range</option>
<option value="18-25">18-25</option>
<option value="26-35">26-35</option>
<option value="36-45">36-45</option>
<option value="46-55">46-55</option>
<option value="56-65">56-65</option>
<option value="66-75">66-75</option>
<option value="75+">75+</option>
</select>
#if ($errors->has('age_range')) <span class="error-message">Age range option is required.</span> #endif
</div>
I suggest putting all you ages in an array and pass that array to view:
$ages = ['18-25','25-50','50-75','75+']; // More dynamic and you can extend in anytime
Now changes in html :
<div class="input--select">
<label>Age Range <span>*</span></label>
<select name="age_range" class="age-range" value="{{old('age_range')}}" required>
// 1. first change which is creating your problem
<option {{ old('age_range') ? "" : "selected" }} disabled>Select your age range</option>
// 2. This is just optimization for short code
#foreach($ages as $age)
<option {{old('age_range') ==$age" ? $selected : ""}} value="{{$age}}">{{$age}}</option>
#endforeach
</select>
#if ($errors->has('age_range')) <span class="error-message">Age range option is required.</span> #endif
</div>
So in point 1 you are always applying the selected with first option.
Suppose your old value was 46-55
your html looks like :
<select name="age_range" class="age-range" value="{{old('age_range')}}" required>
<option selected disabled>Select your age range</option>
<option value="18-25">18-25</option>
<option value="26-35">26-35</option>
<option value="36-45">36-45</option>
<option selected value="46-55">46-55</option>
<option value="56-65">56-65</option>
<option value="66-75">66-75</option>
<option value="75+">75+</option>
</select>
if you take a look at above html there are 2 selected options. Html always picks the first one this is what creating the problem.
Point 1. will check if there is a old value available it will not apply the selected to the first placeholder option.
{!! Form::select('name', $varableyouwanttodisplay, old('name'),
['id'=>'id', 'class' => 'form-control select2', 'data-
placeholder' => 'select','required', 'style' => 'width:100%']) !!}
try like above code.
#php $selected = old('experience') ?: 66; #endphp
and than
{{ Form::select('experience', $experience, $selected, ['class' => 'form-control']) }}
This works in a case when a blade template loads for the first time and doesn't have 'old' value and you need predefined selected option(I.e. 66) for that case.

Laravel: Condition in select dropdown

I want to get the value of my Select Dropdown list from my view to my controller
Is there any way i can get this? :(
Here's my dropdown view
{{ Form::select('status', ['All', 'Absent', 'Late', 'Others']) }}
Here's where i want to condition my selected value
public function filterSummaryStudent()
{
if(Input::has('status') == 'All')
{
(other codes here)
}
I've been getting a blank page when i call this.. Please help. Thank you!
You must specify the value of select dropdown as associative arrays if you want to check the value as a string. Right now your select dropdown code the value is define using numeric index of the array. When you check the Input::has('status') == 'All', of course laravel will return false.
Your code
{{ Form::select('status', ['All', 'Absent', 'Late', 'Others']) }}
HTML Output
<select name="status">
<option value="0">All</option>
<option value="1">Absent</option>
<option value="2">Late</option>
<option value="3">Others</option>
</select>
Correct code
{!! Form::select('status', ['All' => 'All', 'Absent' => 'Absent', 'Late' => 'Late', 'Others' => 'Others']) !!}
HTML Output
<select name="status">
<option value="all">All</option>
<option value="absent">Absent</option>
<option value="late">Late</option>
<option value="others">Others</option>
</select>
If you write like the above code you can check the select dropdown like this.
if(Input::has('status') == 'All') {
// Your code
}

many to many relation in a form view symfony 2

I have a many to many relation between two entities.
I display then a form to add entityA to entityB.
Isn't possible to add a customized form (I mean in the twig view) in order to enable the user sometimes to select one value and sometimes more than one?
when I want the user to select more than one value, I use this
<select multiple>
{% for entity in entitys %}
<option>
{{entity.id}}
</option>
{%endfor%}
</select>
otherwise this
<select >
{% for entity in entitys %}
<option>
{{entity.id}}
</option>
{%endfor%}
</select>
but now the problem is how to submit the form. the
<button type="submit" class="btn btn-info" value="NEXT STEP " />
Here is the whole form
<form method="post">
<select >
{% for entity in entitys %}
<option>
{{entity.id}}
</option>
{%endfor%}
</select>
<input type="submit" />
</form>
no longer submit the form. any ideas plz??
here is my entire twig view
<h2> STEP {{step}} </h2>
<form method="post">
<select >
{% for entity in entitys %}
<option value="{{entity.id}}">
{{entity.id}}
</option>
{%endfor%}
</select>
<input type="submit" class="btn btn-info" />
</form>
<br>
<br>
In your formbuilder you can add some options like in my exemple:
The aim is to map your field to an entity (to setup the list). Don't forget to add a method _tostring to your mapped entity to make symfony able to represent your entity as a text in your select.
In your formType
public function buildForm(FormBuilder $builder, array $options) {
$id = $this->id;
$builder->add(
'addressees',
'entity',
array(
'class' => 'Pref27\MailBundle\Entity\Addressee',
'property' => 'name',
'multiple' => true,
'expanded' => false,
'required' => true,
'label' => 'mail.add.theme';
}
)
);
}
In your formControler
$editForm = $this->createForm(new FormType(), $entity);
return array(
'form' => $editForm->createView()
);
In your view
<form action="{{ path('theControllerActionWitchIsResponsibeOfRecordingIntoDatabase' }}" method="post" {{ form_enctype(edit_form) }}>
{{ form_widget(edit_form) }}
<p>
<button type="submit">Next step</button>
</p>
</form>
The type of field rendered will depend on setting of multiple and expended
select tag expanded=false multiple=false
select tag (with multiple attribute) expanded=false multiple=true
radio buttons expanded=true multiple=false
checkboxes expanded=true multiple=true
you can find more information about entity type in form here : http://symfony.com/doc/2.0/reference/forms/types/entity.html
EDIT:
From your twig view form's action is missing
try to add
<form method="post" action="{{ path("theRouteOfYourControllerWitchRecordTheData")}}">
don't forget to add {{form_rest(form) }} To tell twig to add the CSRF token
and don't forget to add value in your select's option
<select multiple>
{% for entity in entitys %}
<option value="{{entity.id}}">{{entity.name}}</option>
{%endfor%}
</select>

Create a multicolor selectbox on Symfony2

I try to create the following field :
<select name="test">
<option value="1">a</option>
<option value="2">b</option>
<option value="3" style="font-weight: bold; color: red;">c *</option>
<option value="4">d</option>
<option value="5">e</option>
</select>
This creates a 2-color selectbox :
But in Symfony2, I do not know how to apply a class to a single option.
If in my view I do :
{{
form_widget(myForm.test, {
'attr': {
'class': 'red',
}
})
}}
Or if in my form I do :
$builder->add('test', 'choice', array(
'required' => true,
'choices' => array('a', 'b', 'c *', 'd', 'e'),
'attr' => array('class' => 'red'),
));
The attribute is stored into the <select> tag and apply to the whole selectable values.
Edit
I solved the problem using jQuery :
1) in my view I put :
{{
form_widget(myForm.test, {
'attr': {
'class': 'starred-select',
}
})
}}
2) in my javascripts, I put :
$('.starred-select option').each(function() {
if ($(this).text().substr(-2) == ' *') {
$(this).addClass('red');
}
});
Of course, my values can't finish by a star.
How can I apply a class to an <option> tag in Symfony2 ?
You've to override the way your widget choice field is rendered.
Form Theming allows you to customize every part of your form. Even base form blocks can be overriden.
The best method to do this is to copy the default block from form_div_layout.html.twig
(In your case you've to override the widget_choice_options block)
You can also customize your block at different levels of your application. Take a deeper look at the documentation, it includes fully explained examples.

Categories