Create a multicolor selectbox on Symfony2 - php

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.

Related

old multiselect array using select option in laravel 8

am trying to make old values which would be used when am editing but it's returning
htmlspecialchars(): Argument #1 ($string) must be of type string, array giveneverytime
but when i dd the variable i found that it has array but when it reaches the option it changes into error
this is my select in blade
{!! Form::label('functional_area_id', 'Functional Area', ['class' => 'bold']) !!}
<?php
$functionalAreaIds = old('functional_area_id',$jobFunctionalAreasIds);
?>
{{-- this codes works perfect but it doesn't display the relation between child and parent and i want that to be displayed
{!! Form::select('functional_area_id[]', $functionalAreas, $functionalAreaIds, array('class'=>'form-control select2-multiple', 'id'=>'functional_area_id','multiple'=>'multiple')) !!} --}}
<select name="functional_area_id[]" id="functional_area_id" class="form-control select2-multiple" multiple="multiple">
#foreach ($menulist as $category)
<option value={{ $category->functional_area_id }} {{ $functionalAreaIds }} >{{ $category->functional_area }}</option>
#if (count($category->children) > 0)
#include('submenu', ['submenu' => $category->children, 'parent' =>
$category->functional_area])
#endif
#endforeach
</select>
{!! APFrmErrHelp::showErrors($errors, 'functional_area_id') !!}
</div>
this is the controller which fetches the array
public function jobFunctionals()
{
return $this->hasMany('App\JobFunctionalAreas', 'job_id', 'id');
}
public function getJobFunctionalsArray()
{
return $this->jobFunctionals->pluck('functional_area_id')->toArray();
}
You can only output strings using {{ $variable }}, because Blade will run $variable through htmlspecialchars escaping, that's why you get an error trying to output {{ $functionalAreaIds }} which, judging by the name, is an array.
I have no idea what you are including with the submenu partial, but it is likely invalid HTML. The only tags that are allowed within a select element are option and optgroup tags. Optgroups need to be opened and closed around options, so I don't see how this would work in your setup.
Also, you have syntax errors in your option tag:
<option value={{ $category->functional_area_id }} {{ $functionalAreaIds }} >{{ $category->functional_area }}</option>
What do you expect this to do? This would - if it worked at all - result in something like this:
<option value=1 [1,5,6] >Area 1</option>
Which is clearly not valid HTML. What do you expect the array to do after every option value?
To fix the option part of your code, you can do something like this:
<option value="{{ $category->functional_area_id }}" #if(in_array(category->functional_area_id, $functionalAreaIds)) selected #endif >{{ $category->functional_area }}</option>
This will set all options selected that are within the $functionalAreaIds array.
Maybe you should get rid of the code including the submenu when testing, because this is likely to break your HTML too, and then take it from there.
Another tip:
<?php
$functionalAreaIds = old('functional_area_id',$jobFunctionalAreasIds);
?>
can be written in blade like this:
#php($functionalAreaIds = old('functional_area_id',$jobFunctionalAreasIds))

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
}

How to add a custom class to select tag in Symfony2 FormType

I need to add a custom class to my select tag (<select>) generated by an FormType with symfony2.
All options are generated by Symfony
$builder->add(
'birthday',
null,
array(
'label' => 'form.birthday'
, 'translation_domain' => 'FOSUserBundle'
)
)
and the generate code is:
<div id="fos_user_registration_form_birthday" placeholder="Mot de passe" class="form-control">
<select id="fos_user_registration_form_birthday_day" name="fos_user_registration_form[birthday][day]">
<option value="1">1</option>
...
</select>
<select id="fos_user_registration_form_birthday_month" name="fos_user_registration_form[birthday][month]">
<option value="1">jan</option>
...
</select>
<select id="fos_user_registration_form_birthday_year" name="fos_user_registration_form[birthday][year]">
<option value="1994">1994</option>
...
</select>
</div>
And, I need to add a custom class to this:
<select id="fos_user_registration_form_birthday_day" name="fos_user_registration_form[birthday][day]">
I've tried this solution in my html content:
{{ form_widget(form.birthday, {'attr': {'placeholder': 'form.password'|trans, 'class': 'test'}}) }}
But the test class is added to my div (<div id="fos_user_registration_form_birthday" placeholder="Mot de passe" class="form-control"></div>), not to my select tag.
Any suggestions?
In your Form class, you can set the class using the attr option.
You can already do it inside your Form Type, or later in your template, like you just did.
It PROBABLY does not use your 'test' class, because the birthday widget does not use it. Please search your whole project for "birthday_widget" and see if it uses a hardcoded form-control class. If it does, you can write an if statement checking if attr.class is definer or add something like this:
{% for attrname, attrvalue in attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}
Edit: Can you also try rendering each day,month and year separately (I'm not sure if that will work, because I do not know the birthday type), like so...
form_widget(form.birthday.day, {'attr': {'class': 'test'}})
Another thing you can try is to edit your Form Type.
Try to add this after you add method:
$builder->get('birthday')->get('day')->setAttribute('class', 'test'); // Also try with ->get('days')
I'm almost sure something above will work.

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>

Setting the value attribute in a dropdown menu Symfony2

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

Categories