in my create function, I pass my view a list of users which I then display. However, I have changed it to the following
<select class="internalWork" name="internalWork">
<option value=""></option>
#foreach($users as $user)
<option value="{{ $user->userName }}">{{ $user->userName }}</option>
#endforeach
</select>
So I have added an empty option before the list is displayed. This is fine because this tables column allows null input.
In my edit function, I get the list
$users = User::lists('userName', 'userName');
I then pass this to my edit view. In my edit view, I have the following
<div class="form-group">
{!! Form::label('internalWork', 'Internal work for:', array('class' => 'col-sm-5 control-label red')) !!}
<div class="col-sm-7">
{!! Form::select('internalWork', $users, null, ['class' => 'internalWork']) !!}
</div>
</div>
If I selected a user in the create, then when I go to the edit page, that user is selected by default. However, if I do not select a user in the create, on the edit page, the first user in the list is displayed by default.
How can I get it to display an empty input if the database value is null?
Thanks
I think the issue is that although you are providing an empty option in the create view, you are not doing so in the edit view.
If, in your edit function, you populate your array like this:
$users = ['' => ''] + User::lists('userName', 'userName');
then I think the empty option will be selected if userName is empty. This is essentially concatenating an empty pair to the beginning of the $users array that you're passing to the view.
You might also consider constructing the create view in the same way - using the above code to generate your $users array in your create method and then using the Form facade in the view.
I've found this quite useful for working with Form::select(): Creating a Select Box Field
#if (!empty($users)
// the Form
#else
// No result
#endif
OR
array_unshift($users, "There are no users") // Prepend null value to $users
...
// Form::select(..etc
Related
Below is a small part of my data insert form.
My problem is;
The first form object is for the name of the Class room. The field is required and I wanna validate it at server side . In normal it works for sure. But since the next form object is an dropdown menu which get filled from a table of my database, the validation doesn't work. When i post it with empty class room field I get a error.
Normaly it is expected that the server side validation work and stop the posting action right ?
But it doesn't.
What do I miss here ? Thank you.
PS: The teacher field in DB is nullable and when i type something in the class room textbox the form works w/o any problem.
...
...
<div class="col-8 form-floating p-2">
<input type="text" asp-for="AddClassRoom.Class" class="form-control" />
<label asp-for="AddClassRoom.Class"></label>
<span asp-validation-for="AddClassRoom.Class" class="text-danger"></span>
</div>
<div class="col-8 form-floating p-2">
<select class="form-select" asp-for="AddClassRoom.Teacher" asp-items="#(new SelectList(Model.ApplicationUser.OrderBy(x => x.NameSurname).ToList(),"Id","NameSurname"))">
<option value="">select...</option>
</select>
<label asp-for="AddClassRoom.Teacher"></label>
<span asp-validation-for="AddClassRoom.Teacher" class="text-danger"></span>
</div>
...
...
With reference to you comment:
Error is; null parameter(source). Well this is ok, i know it. But there must be a simple way to validate an insert form who has an Database driven content dropdown menu. Post and don't get null after server side validation.
It seems that the dropdown values are not populated after posting the form. Since you have the dropdown values are coming from DB, you need to get its items again from DB after posting the form, so the razor page can fill it again.
More support can be provided if you share your backend code.
[Sample]
Here is a basic sample depending on your code;
<select class="form-select" asp-for="AddClassRoom.Teacher" asp-items="#(new SelectList(Model.ApplicationUser.OrderBy(x => x.NameSurname).ToList(),"Id","NameSurname"))">
<option value="">select...</option>
</select>
Backend:
public ActionResult OnGet() {
// ...
ApplicationUsers = GetApplicationUsersFromDb();
Return Page();
}
public ActionResult OnPost() {
// ...
ApplicationUsers = GetApplicationUsersFromDb();
Return Page();
}
I need to keep the checked checkboxes in the form as checked after I get the validation errors in the Controller.
Actually I find quite horrendous my implementation of the checkboxes in my form.
Could you please provide some advise? Thanks
<div class="form-group">
{!! Form::label('call', 'Llamar:', ['class' => 'control-label']) !!}
{!! Form::checkbox('call', isset($category)?(bool)$category->call:true, ['class' => 'form-control']) !!}
</div>
For the checkbox part, I did not use Laravel Forms. I used normal html "input" tag instead, and used "old" to check for previous value
<input type="checkbox" name="call" value="1" {{(old('call') == "1") ? 'checked': ''}}>Call
Try using old to check the previous value and set the value to checked or not based on that.
You can do it via the form builder much easier like this:
{!! Form::checkbox('call', 1, false, ['class' => 'form-control']) !!}
call = your checkbox name
1 = your checkbox value if it's checked (change to whatever you want)
false = don't load it checked on first page load (setting true will load it always checked)
['class' => 'form-control'] = it will add the class to it
That's all.
You don't need to worry about any kind of values, it will be set automatically.
I am trying to make a select box that return value from $collection, but it gives me index of the selection instead of value.
screenshot:output of my code
screenshot:browser source code view
<div class="form-group">
{!! Form::label('Supervisor') !!}<br />
{!! Form::select('supervisor_id', $lecturers, null,
array('placeholder' => '----------------','class' => 'form-control')) !!}
</div>
and when it's show in browser source code view:
<option value="">----------------</option>
<option value="0">1111111111</option>
<option value="1">1212121212</option>
Anyone who know the syntax of laravel form to make this dynamic form gives value of $lecturers please help.
Ok here we go.
First in your controller, when you are getting the lecturers list, make sure you pluck just the name and the id...in this order:
$lecturers = Lecturer::pluck('name', 'id');
Then in your view:
{{Form::select('lecturer_id', $lecturers, null, ['class' => 'form-control'])}}
Thats all.
The array of lecturers, that you plucked will be divided into "id" and "values", hence the order of plucking is important.
Now, in your form source, you will see that the option value will be lecturers ids like "1, 2, 3" etc while the "selectable" options shown to users will be the names of the lecturers.
Like this:
<select class="form-control" name="lecturers_id"><option value="1">John Doe</option><option value="2">Jane Doe</option></select>
Try these and lets know your result.
I have a multi-step form in laravel where I pass the session variables from one view to the other and everything works ok.
This is part of my form
<div class="panel-body">
{!! Form::open(array('url' => '/post-quote')) !!}
<div class="form-group">
{!! Form::Label('brand', 'Brand:') !!}
<select class="form-control" name="brand" id="brand">
<option value="{{Input::old('brand')}}" selected="selected">{{Input::old('brand', 'Please select a Brand')}}</option>
#foreach($brands as $brand)
<option value="{{$brand->id}}">{{$brand->brand}}</option>
#endforeach
</select>
</div>
Here is part of my controller
public function quote()
{
$brands = Brand::orderBy('brand')->get();
return View::make('frontend.step1', compact('brands'));
}
The issue I got is that I am passing the id for each option value in the select and after validation, the Input::old populates the id value and it doesn't look right to display a number instead of the brand name.
Question: is there anyway to get input::old with the {{$brand->brand}} instead of the id?
My other option is to pass as a value for each option the brand name, however I dont know how to get the id for my input in the controller.
I hope you get what I am trying to achieve.
Thanks
Did you try passing the brands as an array? Like,
$brands = Brand::orderBy('brand')->lists('brand','id');
return View::make('frontend.step1', compact('brands'));
Then in your view you can use the Form::select instead of creating the select manually. Something like this:
{!! Form::select('brand',$brands, Input::old('brand'),['class' => 'form-control']) !!}
Give it a try and let me know if it works, there are some others things you can try, like using Form::model instead of Form::open (I would go with this approach)
you can pass data to next user request by using flash method like this
$request->flash()
then retrieve it in blade template with global old helper function which gives you old input data,
{{ old('brand') }}
$brands = Brand::orderBy('brand')->lists('brand','id');
return View::make('frontend.step1', compact('brands'));
Then in your view you can use the Form::select instead of creating the select manually. Something like this:
{!! Form::select('brand',$brands, Input::old('brand'),['class' => 'form-control']) !!}
I would like to create a requirement that if nothing is selected from a drop down field in my contact form that a message will come up saying "Please choose", and the form will not be able to be submitted unless something is chosen. I have gotten requirements to work on all of my text input forms, but cannot figure out how to create one for the drop down field.
The drop down HTML looks like this:
<div class='container'>
<label for='destemail' > Which department are you trying to reach?*</br> You must select a department.</label></br>
<select name="destemail" id="destemail">
<?php foreach ($emailAddresses as $name => $email) { ?>
<option value="<?php echo htmlspecialchars($name); ?>"><?php echo htmlspecialchars($name) ; ?></option>
<?php } ?></select>
<span id='contactus_destemail_errorloc' class='error'></span>
</div>
I got the other form requirements to work like so:
The HTML -
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
</div>
The Javascript -
<script type='text/javascript'>
<![CDATA[
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
</script>
The PHP -
//name validations
if(empty($_POST['name']))
{
$this->add_error("Please provide your name");
$ret = false;
}
I tried the exact same coding for the drop down but with the different id names where appropriate, and it didn't work. Why doesn't this same method work for the drop down?
Help much appreciated!
I can't see what the Validator() code is doing, but you can just check to see whether the select field is empty using Javascript or jQuery.
jQuery way:
if( !$('#destemail').val() ) {
alert('Empty');
}
The problem may lie in that your select box actually does have a value, which is whatever the first value printed out in it is. The Validation function may be checking for any value, and since the select does have one, it returns as valid.
You could set up a default value to show first, something like "Please select a Department", and then do the jquery/javascript check for that text. If it exists, then you know an option has not been selected.