I have a dropdown called designation, where a user will select one of it, and after submitting it, if there is some error then I want to select the selected designation.
I am using this in laravel 5.4.
Controller
$info = DB::table("designation")
->where('status','=',1)
->pluck("name","id");
return view('regUser.add',['check' => 'userList','designation' => $info]);
View Files
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" />{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
Now if the validator found some error then I want to select the previously selected one.
How can i achive this in laravel 5.4.
After submiting the form it comes to addUserInformation function, where I validate the user information which have this piece of code
public function addUserInformation(Request $request){
$this->validate($request, [
'name' => 'required|string|min:5',
'email' => 'required|string|email|unique:users,email',
'designation' => 'required|exists:designation,id',
'password' => 'required|min:6',
'confirm_password' => 'required|same:password',
'userimage' => 'required|image',
]);
$selectedID = $request->input('designation');
}
Larvel passes the inputs back on validation errors. You can use the old helper function to get the previous values of form. A simple comparison should do the trick.
<div class="form-group {{ $errors->has('designation') ? ' has-error' : '' }}">
<label for="designation">Designation</label>
<select id="designation" name="designation" class="form-control">
<option value="">--- Select designation ---</option>
#foreach ($designation as $key => $value)
<option value="{{ $key }}" {{ old('designation') == $key ? 'selected' : ''}}>{{ $value }}</option>
#endforeach
</select>
#if ($errors->has('designation'))
<span class="help-block">
<strong>{{ $errors->first('designation') }}</strong>
</span>
#endif
</div>
You have to maintain the state of old input by using return redirect() like:
return redirect('form')->withInput();
Retrieving Old Data
To retrieve flashed input from the previous request, use the old method on the Request instance.
$oldDesignation = Request::old('designation');
and check it like:
#foreach ($designation as $key => $value)
$selected = '';
#if( $value == $oldDesignation )
$selected = 'selected="selected"';
#endif
<option value="{{ $key }}" {{ $selected }} />{{ $value }}</option>
#endforeach
Reference
Related
I am trying to show roles which is related to user but unfortunately userRoles are not showing related to user in selection option, please help me how can I match that thanks.
Note :- I am using spaite laravel permission docs
controller
public function edit(User $user)
{
$data = [
'isEdit' => true,
'user' => $user,
'roles' => Role::where('guard_name', '=', 'web')->select(['id', 'name'])->get(),
'userRole' => $user->getRoleNames(),
// i am getting userRole in array related to user
// ['employe']
];
// return $data['userRole'];
return view('cms.user_management.add-user', $data);
}
html view
<div class="col-md-6">
<div class="form-group">
<label>Role <span class="text-danger">*</span></label>
<select class="form-control" name="roles[]">
<option selected="selected" disabled >please
select</option>
#foreach ($roles as $item)
<option value="{{ $item->name }}"{{ $userRole ==
$item->name ? ' selected' : '' }}>{{ $item->name }}</option>
#endforeach
</select>
</div>
<span class="text-danger">{{ $errors->first('roles') ?? null }}
</span>
</div>
Try the following changes in your HTML
If $userRole is array than check if $item->name exists in array, using in_array.
'userRole' => $user->getRoleNames()->toArray(),
html view
{{ in_array($item->name, $userRole) ? 'selected' : '' }}
<div class="col-md-6">
<div class="form-group">
<label>Role<span class="text-danger">*</span></label>
<select class="form-control" name="roles[]">
<option selected="selected" disabled>please select</option>
#foreach ($roles as $item)
<option value="{{ $item->name }}"{{ in_array($item->name,$userRole) ? 'selected' : '' }}>{{ $item->name }}</option>
#endforeach
</select>
</div>
<span class="text-danger">{{ $errors->first('roles') ?? null }}</span>
</div>
you can use this to get the roles asssociated with current user or
Auth::user()->roles->pluck('name');
for any specific user roles.
User::find($id)->roles->pluck('name')
I added a drop down list in the user registration form in Laravel. Now I want to make a form to edit it but I'm stuck.
What I did is I made a drop down list which a new user can register where he/she lives. I used a list of cities(pref.php) in the configuration folder to make this drop down list. I want the user to be able to see the cities that they have registered default when opening the edit form and then change it or leave it alone but I couldn't figure out how to do this.
Here are my codes.
editprofile.php
<form action="/profile" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('patch') }}
<p>
<label><b>name</b><br>
<input type="text" name="name" value='{{ $user->name }}'><br>
</label>
</p>
<p>
<label><b>location</b><br>
<select type="text" name="location" value="{{ $user->prefName }}">
#foreach(config('pref') as $key => $score)
<option value="{{ $key }}">{{ $score }}</option>
#endforeach
</select>
</label>
</p>
<p>
<label><b>mail adress</b><br>
<input type="text" name="email" value='{{ $user->email }}'><br>
</label>
</p>
<p>
<label><b>profile image</b><br>
<input type="file" name="profile_image"><br>
</label>
</p>
<input type="hidden" name="id" value="{{ $user->id }}">
<input type='submit' value='edit' class="btn btn-primary mt-3">
</form>
ProfileController.php
public function edit()
{
$user = Auth::user();
return view('profile.editprofile', ['user' => $user]);
}
public function update(ProfileRequest $request, User $user)
{
$user = User::find($request->id);
$user->name = $request->name;
$user->email = $request->email;
$user->location = $request->location;
if ($request->hasFile('profile_image')) {
Storage::delete('public/profile_image/' . $user->profile_image);
$path = $request->file('profile_image')->store('public/profile_image');
$user->profile_image = basename($path);
}
$user->update();
return redirect('/profile');
}
pref.php
<?php
return array(
'0' => 'not selected',
'1' => 'New York',
'2' => 'Los Angeles',
'3' => 'Dallas'
);
I thought this page had a similar problem but it was a little different.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
to make an option selected you have to put selected property in that option. putting value on select won't work. you can do it like
<select type="text" name="location">
#foreach(config('pref') as $key => $score)
<option value="{{ $key }}" {{ $user->location == $key ? 'selected' : '' }}>{{ $score }}</option>
#endforeach
</select>
In your edit form you had a particular user information by it ID in one array after that you get the user into a edit page right, using that array you can check with option box like below example
<select type="text" name="location" value="{{ $user->prefName }}">
#foreach(config('pref') as $key => $score)
<option <?php echo($get_array_by_user_id->table's_exist_location_value == $key) ? 'selected' : ''; ?> value="{{ $key }}">{{ $score }}</option>
#endforeach
</select>
I think it is working exactly to you : - )
Thank You,
I tried to update specific item but it was error 'Call to a member function update() on null'.
I tried to change ->update($data) with ->insert($data) before and it works.
Controller:
public function update(Request $request, $id)
{
$this -> validate($request, array(
'gamename' => 'required|min:3',
'price' => 'required|int|min:1',
'genre' => 'required',
'releaseddate' => 'required|date',
'picture' => 'required|mimes:jpeg,jpg,png,gif'
));
$gamename = $request->input('gamename');
$genre = $request->input('genre');
$price = $request->input('price');
$releaseddate = Carbon::parse($request->input('releaseddate'));
$picture = $request->file('picture')->getClientOriginalName();
$data=array('gamename' => $gamename, 'genre'=>$genre, 'price'=>$price,'releaseddate'=>$releaseddate,'picture'=>$picture );
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->find($id)->update($data);
return redirect('managegame');
}
View:
<form action="/update/{id}" method="post" id="registerform" enctype="multipart/form-data">
<div class="errorpop{{ $errors->has('genre') ? ' has-error' : '' }}">
<label for="genre" class="">Genre</label>
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>
{id} not a value. You must have value for {id} .
Example: action="/update/1"
<form action="/update/1" method="post" id="registerform" enctype="multipart/form-data">
<div class="errorpop{{ $errors->has('genre') ? ' has-error' : '' }}">
<label for="genre" class="">Genre</label>
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>
Then to update you use method where('id', $id) replace find($id)
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->where('id', $id)->update($data);
https://laravel.com/docs/5.5/queries#updates
Make sure you got the object
$game = DB::table('games')->
join('genres', 'games.genreid', '=', 'genres.genreid')->where('id',$id)->get();
//make sure you have the desired object.then
$game->update($data);
I'm nor sure this line works as you expect
DB::table('games')->join('genres', 'games.genreid', '=', 'genres.genreid')->find($id)->update($data);
What are you trying to update? games or genres ? You can't update 2 tables at once like that. You'd need to find the games row to update, update that that, and the joined table row, and update that, cannot do it all at once.
But the fact that you're trying to update 2 tables from one simple form, in the same method suggests that your tables is not properly laid out?
id)->update($data);
return redirect('managegame');
}
View:
has('genre') ? ' has-error' : '' }}">
Genre
<div class="">
#foreach($genres as $genre)
<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>
#endforeach
#if ($errors->has('genre'))
<span class="help-block">
<strong>{{ $errors->first('genre') }}</strong>
</span>
#endif
</div>
</div>
in my controller, I am passing a list of clients to the view
public function edit(Project $project)
{
$clients = Client::select('clientName', 'id')->get();
return View::make('projects.edit', compact('project', 'clients'));
}
Now in my view, I am currently doing this
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
<select class="clientName" name="clientName">
#foreach($clients as $client)
#if (Input::old('clients') == $client->id)
<option value="{{ $client->id }}" selected="selected">{{ $client->clientName }}</option>
#else
<option value="{{ $client->id }}">{{ $client->clientName }}</option>
#endif
#endforeach
</select>
</div>
</div>
What I am trying to do is have the default select option set as the old input. At the moment, the select displays with all the clients, but the old value is not default.
How would I go about making it the default option?
Thanks
Update
I do a alternative way I am trying. In my edit function I do
public function edit(Project $project)
{
$clients = Client::lists('clientName', 'id');
return View::make('projects.edit', compact('project', 'clients'));
}
And then in my view I do
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::select('clientName', $clients, Input::old('clients'), ['class' => 'clientName']) !!}
</div>
</div>
Seem to have the same issue though, the client is not the old client as the default selected option.
Thanks
Your select name is clientName but your old input is looking to a field with the name clients.
The following should work:
<option value="{{ $client->id }}" {!! old('clientName', $project->client->id) == $client->id ? 'selected="selected"' : '' !!}>{{ $client->clientName }}</option>
Trying to improve the code of my app and just migrated to L5. I used to call models in my views and I know this is not best practice - I should separate data calling and views completely.
However how do you deal with a situation like this:
<div class="field">
<label for="country">Country<sup>*</sup></label>
<select class="" id="country" name="country">
<option value="{{{ old('country') ? old('country') : '' }}}">{{{ old('country') ? App\Country::find(old('country'))->country_name : '' }}}</option>
#foreach ($countries as $studio_country)
<option value="{{ e($studio_country->id) }}">{{ e($studio_country->country_name) }}</option>
#endforeach
</select>
#if ($errors->has('country'))
<div class="alert alert-warning" role="alert">
{{ $errors->first('country') }}
</div>
#endif
<br>
</div>
Basically if there is an input and the input did not pass the validation the page refreshes with the old input and the error message. I need to extract the name of the country from the DB since I only have its ID.
You would want to do something like this:
<select id="country" name="country">
#foreach ($countries as $studio_country)
<option
value="{{ $studio_country->id }}"
{{ $studio_country->id === old('country') ? 'selected' : '' }}>
{{ $studio_country->country_name }}
</option>
#endforeach
</select>