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.
Related
I am overriding the register page (overriding the Customer object) ; I have added "Type", which is a ChoiceType expanded (3 radio buttons), and I have added the defaultAddress fields (in which I have added 3 fields).
When I display the form, all these fields have a red star to show there are required, but when I submit the form, if I don't put anything in these fields, the form is submitted anyway and I have a database error because these fields are empty.
Here is my code :
CustomerRegistrationTypeExtension.php :
$builder->add('type', ChoiceType::class, [
'choices' => array('Particulier' => Customer::TYPE_PARTICULIER, 'Professionnel' => Customer::TYPE_PRO, 'Projet à but non lucratif' => Customer::TYPE_PROJET),
'expanded' => true,
'label' => 'Vous êtes',
'choice_attr' => array('onclick' => 'alert(\"click\")')
])
->add('siren', TextType::class)
->add('denomination', TextType::class)
->add('defaultAddress', AddressType::class);
AddressTypeExtension.php
$builder->add('showOnMap', CheckboxType::class)
->add('geocodeLat', HiddenType::class)
->add('geocodeLng', HiddenType::class);
_address.html.twig :
{{ form_row(form.showOnMap, {'label' : 'address.showMap.label'}) }}
{{ form_row(form.geocodeLat)}}
{{ form_row(form.geocodeLng)}}
_form.html.twig
{{ form_row(form.type) }}
Any idea ?
Thanks !
Red asterisk near the field is just an UI feature. To require some fields, you must specify theirs validation configuration. Check out Symfony validation documentation to get required info, all of it should perfectly work in Sylius ;)
One important thing - remember to set sylius in groups parameter when defining constraints, it is a default validation group in Sylius.
Sorry if the title is misleading...
I have the following to create a select box using the laravel Form facade:
{{ Form::select('category_select', $categories_select, null, array('class' => 'selectpicker show-tick', 'data-live-search' => 'true', 'id' => 'category_select')) }}
Now $catgories_select is a pluck() of id and name.
I want to do the same for another select (Tax rules) but there I want to have it like the following:
<option value="id">$value1 ($value2)</option>
How can I do this?
If you pluck the models before the view, you'll need two collections. But you could just do one query, then pluck inline. Let's assume $categories is your queried collection before the pluck:
{{ Form::select('category_select', $categories->pluck('name', 'id'), null) }}
Then on the other you'd pluck a mutated property:
{{ Form::select('category_select_tax', $categories->pluck('compositeName', 'id'), null) }}
And then, on your Category model you'd have:
public function getCompositeNameAttribute()
{
return "{$this->name} ({$this->value2})";
}
I have to edit a few value's from the database.
with a textfield or area i can just fill the formfield with the old date like this
{{ Form::text('hours', Input::old('hours', $vacature->hours), array('class' => 'form-control', 'placeholder' => 'Aantal uren')) }}
where Input::old('hours', $vacature->hours) takes care of the old input retrieved from the model.
When i try do to the same with select fields, it does not work.
{{ Form::select('employmentType',Input::old('employmentType', $vacature->employmentType), array('vast' => 'Vast dienstverband', 'Freelance' => 'Freelance'), null, array('class' => 'form-control')) }}
I'm stuck on this for quite a while now. So i hope i can get some help here!
You should rearrange the passed arguments:
{{ Form::select('employmentType', array('vast' => 'Vast dienstverband', 'Freelance' => 'Freelance'), Input::old('employmentType', $vacature->employmentType), array('class' => 'form-control')) }}
Basically you should pass:
field name
options (key => value pairs)
selected value (you set old value if there is one or a default value if there isn't)
field attributes
or:
Form::select('fieldName', $options, $selectedValue, $fieldAttributes)
If you don't succeed at first try "slicing" the problem into steps:
see what do you get as an "old" value, see how the select behaves when you pass a static slected value to it etc.
Take care
I believe that when you use Laravel's form and you bind it to a model, you can just use the Redirect::back()->withInput(); method and laravel will do the job for you.
here's how you can do this from the Laravel doc :
Form::model($user, array('route' => array('user.update', $user->id)))
Doc page.
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
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();
}