Laravel dropdown list - php

I'm using Laravel framework and i have two dropdown lists of which both are reading data from the database tables,
the first one it read all the records from the table and populate it on the select list
here is my code:
<div class="form-group">
{{Form::select('advertiserName', Advertiser::all()->lists('advertiserName', 'advertiserId'))}}
</div>
it display the advertiser name and also passes the id on the advertiser.
The second dropdown i want it to display all the Brands related to the above selected advertiser.
here is my code:
<div class="form-group">
{{Form::select('brandName', Brand::where('advertiserId', '=', '3')->lists('brandName', 'id'))}}
</div>
The advertiserId is the foreign key of the advertiser and 3 must be replaced by the the advertiserId you selected on the first dropdown list, basically i want to pass variable from the first select list to the second one
Thank you

Basically you need to use AJAX to get data for Second Dropdown based on option selected from first dropdown.
Create Second Dropdown inside specific div and After ajax Call replace contect of div from ajax response.

As stated, the best way to achieve this is via an AJAX request. Here is an example of how you can achieve this functionality.
Firstly create a view partial that renders the select box for brands. Something like this (this code is based on Bootstrap 3):
{{ Form::label('brandName', 'Brand', ['class' => 'control-label col-sm-2']) }}
<div class="col-sm-10">
{{ Form::select('brandName', $brands, null, ['class' => 'form-control']) }}
</div>
Now, in your routes.php file add the following route:
Route::get('brand-list/{id}', ['as' => 'brands', 'uses' => 'BrandsController#brandList']);
In your BrandsController.php file (or whatever controller your using to handle this) add a method called brandList();
public function brandList($id)
{
// Return an array of brands for the selected advertiser name ID if available
$brands = $this->brand->where('advertiserId', $id)->lists('brandName', 'id'); // I'm using dependency injection here so you'll need to assign your Brand model to the $this->brand property of this classes constructor method
if ( ! isset($brands))
{
$brands = ['No brands available' => null]; // return a generic array containing 1 item with a value of null so you can handle it in your view. You could also return something else here such a boolean of false and then handle that in your AJAX request to return an error or info message
}
return View::make('brands.partials.select', compact('brands'));
}
Now for the AJAX:
$('#advertiserName').change(function(e) {
var advertiserId = $(this).val();
var url = '/brand-list/' + advertiserId;
$.get(url, function(data) {
$('.brands').html(data); // The returned view with the brand select input
});
});
Then in your initial form view you'll want to create an empty div with a class of .brands that we'll use to populate with the HTML returned via our AJAX request. Something like this if you're using Bootstrap 3 for example:
<div class="form-group brands"></div>
This should work as you need but I haven't tested this code, so if you have any issues let me know. Obviously this is generic code based on the info available and there are many ways to skin a cat.

Related

Form dropdown menu passing array as object

I'm trying to pass trough form dropdown selection but I can't pass array(the rest of the form is using objects. This is my code
Controller
$var->user = $request->users->id;
view
{!! Form::select('users', $users,null, ['placeholder' => 'Pick a user']) !!}
One solution is converting array to object using eloquent, how can that be done
If you want to get selected user's ID, I guess you need to do this:
$request->users
You're getting "Trying to get property of non-object" error, because $request->users is not an object.
If you want to get the user list you can follow this:
In Controller:
$user_id = UserModel::lists('username','id')->all();
"usename" and "id" is user-table fields.you can replace any other fields which you will show in user list.
In view:
{!! Form::select('user_id', $user_id,Input::old('user_id'),['placeholder'=>'select user']) !!}

Laravel Select Box

I'm trying to figure out how I can structure my Laravel select menu so that it shows up as this for a final render. Has anyone done such a thing.
The location is a property of the arena object.
<option value="arena_id">Arena Name - Location</option>
{{ Form::select('arena_id', [ null => 'Please Select'] + $arenas, null, ['id' => 'arena_id']) }}
I asssume $arenas comes from something like Arena::where('foo', bar)->get(), but with get() you will get an instance of Illuminate\Database\Eloquent\Collection instead of an actual array which is what you want in Form::select.
So what you need to do is to use lists($field, $key), it will fetch you rows and return it as an array.
$arenas = Arena::where('foo', bar)->lists('name', 'id');
There is a code example here with some comments from users if you want to learn more.
You can use pluck function for getting the results as array
refer https://laravel.com/docs/5.1/collections#method-pluck
$select = $this->all()->pluck('title', 'id');
Then you can use below sample code for creating select box with selected option in blade template
{{ Form::select('name',$select,'selected option id',['class' => 'form-control']) }}

How to display textbox value dynamically which is get from database using laravel

I got value from database and then i need to set those value to textbox. I have created a controller file with the method name of edit look like below
userdata.blade.php:
public function edit($id)
{
echo "You have clicked edit link".$name;
$editdata = DB::table('newuser')->where('Id','=',$id)->get();
return View::make('editdata',array('list' => $editdata));
}
I have passed array of value as parameter to the view file.now i need to diaplay the value of name to textbox.how to do that in html page using laravel. My html page look like below
editdata.blade.php:
<html>
<head></head>
<body>
<div>
{{Form::open(array('url' => 'login', 'method' => 'post'))}}
{{Form::label('name','Name',array('id'=>'label-name'))}}
{{Form::text('name',{{$list->Name}}}}
{{ Form::close() }}
</div>
</body>
</html>
can anyone tell me that what mistake i did.Thanks in advance
Just remove the curly brackets, you are already "inside" PHP code and don't need them:
{{ Form::text('name',$list->Name) }}
Also you get a collection from your controller you probably want to do:
$editdata = DB::table('newuser')->where('Id','=',$id)->first();
Or even:
$editdata = DB::table('newuser')->find($id);
get() returns a collection (multiple rows) and not the model itself. You can use User::find($id) which gives you direct access to the model with the specified Id.
When not using eloquent just replace get() with first()

Laravel/Blade Drop Down List - For more than one field

I'm trying to use blade to display a dropdown list from table data. The problem I have, is that I want to display the results of two fields in the table concatenated, not just one.
So I want something to render something like;
<select id="agreement_type" name="agreement_type">
<option value="1">Agreement Field 1 - Agreement Field 2</option>
<option value="2">Agreement Field 1 - Agreement Field 2</option>
<option value="4">Agreement Field 1 - Agreement Field 2</option>
</select>
My controller currently looks like this;
$agreements = Agreement::lists('agreement_type','id');
return View::make('client_agreements.create')
->with('agreements', $agreements);
My blade view currently looks like this;
<div class="form-group">
{{ Form::label('agreement_type', 'Agreement type') }}
{{ Form::select('agreement_type', $agreements) }}
</div>
I have tried to amend the view and controller in various ways to get the desired output. But can't get it to work.
I want to display agreement_type and level and have the id set as the value so I tried;
$agreements = Agreement::lists('agreement_type'.'level','id');
But this just displays level as the value and completely ignores id.
This is the simplest method. Just use a foreach loop to build the options array:
$agreements = Agreement::all();
$agreementOptions = array();
foreach($agreements as $agreement){
$agreementOptions[$agreement->id] = $agreement->agreement_type.' '.$agreement->level;
}
return View::make('client_agreements.create')
->with('agreements', $agreementOptions);
However you can also define an attribute accessor in your model. You can use that to create new properties that can be accessed normal, but you can run logic to generate them (like combining to attributes)
public function getSelectOptionAttribute(){
return $this->attributes['agreement_type'].' '.$this->attributes['level'];
}
And then you can use lists:
$agreements = Agreement::all()->lists('select_option', 'id');
(Laravel converts SelectOption (studly case) from the method name to select_option (snake case) for the attribute, so don't get confused by that)

How to mark selected items as checked in laravel multiselect dropdown

I am using this multiselect dropdown plugin . I can get all the ids of the selected items in the dropdown during the store method. However during the edit method when ever i am trying to load the entity that has multiple values , i am unable to mark the items as checked in the dropdown.
so for example -
Suppose I am working with Contacts. Each contact can belong to many categories. There is a belongsToMany relationship between the contacts and the categories. Whenever I am adding a new contact (and if the user has selected many categories) i get the id of all the categories and assign it to the contact. Now when I am trying to load the contact again, i have to display the list of categories that were selected for this contact - which i have ben unable to do so till now.
Travis answers really helped me a lot. Hence I am marking this as the correct answer. However there were some updates that I had to do . Following is what I had to do ..
#if(isset($contact))
<?= Form::select(
'category_ids[]',
Category::lists("name", "id"),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control multiselect',
'multiple'
]
)?>
#else
{{ Form::select("category_ids[]", Category::lists("name", "id"), Input::old("category_id"), array( "class" => "form-control multiselect" , "multiple" => "multiple" )) }}
#endif
I am using the same form for the create and edit operations , so in the create form , it was throwing me an error on the contact->categories line which is true because in the create method the contact is null. Hence the check.
Here's how I accomplish multi-selects in Laravel 4:
<?= Form::select(
'category_ids[]',
App::make('Category')->lists('name', 'id'),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control',
'multiple'
]
)?>
The resulting select markup looks like this:
<select class="form-control" multiple="multiple" name="category_ids[]">
<option value="1" selected="selected">category 1</option>
<option value="2">category 2</option>
</select>
And then, when you update, you'll need to add this line after validating your model:
$contact->categories()->sync(Input::get('category_ids'));
Use this in both your create and edit forms. In your create action,
$contact->categories() will be empty, so the select will not be populated, but in the edit action, you will get the properly selected values.
Edit: In order to share the form like this, you'll need to pass in a new instance of the contact model in your create action like so:
public function create()
{
$contact = App::make('Contact');
return View::make('contact.create', concat('contact'));
}
In your shared form, $contact will always be available even if it's not yet persisted.

Categories