Custom select list in Laravel Way - php

I am able to generate the select list in Laravel Way, But how can i insert a custom element in it.
Here is my form:
<li>
<?php
$countrya[] = 'Country';
?>
#foreach($countries as $row)
<?php
$countryarr[$row->CountryID] = $row->Country;
?>
#endforeach
{{ Form::select('ClientSales', $countryarr, '',
array('class' => 'choiceSelect fi_top', 'id' => 'CountryName')); }}
</li>
Here it will generate the list of countries,
The problem is it will display the first country name in the first list, but i want to insert a dummy value inside it.
i.e., <option value="">Choose any Country</option>
How can I do this in Laravel ?

The problem here is:
$countrya[] = 'Country';
I don't know what it's and if you use it, but you need here (after / before above line or instead of it):
$countryarr[''] = 'Choose any Country';
because you use $countryarr in your select. You should also create array with data to View rather in controller and not in Blade template

Check This one
<li>
<?php
$countrya[] = 'Country';
$countryarr[0]='Choose any Country'; //Here is the code I have added
?>
#foreach($countries as $row)
<?php
$countryarr[$row->CountryID] = $row->Country;
?>
#endforeach
{{ Form::select('ClientSales', $countryarr, '', array('class' => 'choiceSelect fi_top', 'id' => 'CountryName')); }}
</li>

Well you have to make your initial item for $countryarr
$countryarr = ['Choose any Country'];
It will create <option value="0">Choose any Country</option>
So its ID will become zero. Its up to you now how you will evaluate the zero when you submit it.

Related

How to looping data in select tag with Laravel 5

Hi i'm beginner using Laravel 5 Framework
i want to ask. how to looping data in select tags with Laravel 5 Framework.
If i using PHP Native like this:
<select name="handphone">
<?php
include "connection.php";
$data_get = mysqli_query($con,"select * from handphone");
while ($get=mysqli_fetch_object($data_get)) {
?>
<option value="<?php echo $get->idphone ?>"><?php echo $get->namephone ?>
</option>
<?php } ?>
</select>
How To looping data in select tags using Laravel 5 ?
In Laravel you will use something like this
$handphones = DB::table('handphone')->all();
This will get all the records from the handphone table.
In your view use the foreach to loop through the results like this.
<select>
#foreach($handphones as $handphone)
<option value="{{$handphone->idphone}}">{{$handphone->namephone}}</option>
#endforeach
</select>
I hope this answers your question.
There is a cleaner way to do it without a loop:
{!! Form::label('handphones', 'Handphones') !!}
{!! Form::select('handphones', $handphones , null, ['class' => 'form-control', 'required']) !!}
The values have to be stored as the key and the the displayed names as the value.
If you want to select an option by default you pass it as the third parameter.
You need to include "illuminate/html": "5.0.*#dev" because the html class is not embedded any more.

Select drop down from table array

Here is part of my controller;
$agreements = Agreement::all();
print_r($agreements) //this works and displays an object/array with the details!
return View::make('individual_agreements.create')
->with('individual', $individual)
->with('agreements', $agreements)
->with('content_title', 'Create new individual agreement');
Here is part of my view;
<div class="form-group">
{{ Form::label('agreement_name', 'Agreement name') }}
{{ Form::select('agreement_name', $agreements->agreement_name) }}
</div>
I have a field called agreement_name in the table.. All I want to do is turn that in to a dropdown in the most efficient Laravel/Eloquent way as possible.
I keep getting the standard "agreement_name not defined" error and I cannot find a suitable example anywhere online having looked for over an hour now.
If you need the agreements for something else on the same page try
<div class="form-group">
{{ Form::label('agreement_name', 'Agreement name') }}
{{ Form::select('agreement_name', $agreements->lists('agreement_name', 'agreement_name')) }}
</div>
This will get all the agreements names within your agreements collection and allow them to be used within the select drop down. First parameter is the column and second is the key.
Else just change your query to;
$agreements = Agreement::lists('agreement_name', 'id');
You should do this
$agreements = Agreement::lists('agreement_name', 'id');
all return you all columns in table, so that's why your code wont work
The way you have this set up allows for the use of a foreach loop to list through and display results:
<select name="agreement_name" class="">
<option value="">- Select -</option>
#foreach($agreements AS $agreement)
<option value="{{ $agreement->id }}">{{ $agreement->agreement_name }}</option>
#endforeach
</select>
Since your $agreements is an array of elements, calling $agreements->agreement_name wouldn't work, while $agreements[0]->agreement_name probably would. If you want to use the Form::select() option, you'll need to use a different method of getting your agreements. Check the other answers for that solution.
Hope this provided some insight!
Edit
I should note that this isn't the Laravel Way of doing things, but it is certainly viable.

How to mark select items as checked in a multiselect dropdown with optgroups laravel

I am using this select 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.
Suppose I am working with schools and each school can belong to many categories so here is a belongsToMany relationship between the contacts and the categories. On the select dropdown create form, my categories are grouped in optgroup depending on which type they belong to... I have a oneToMany relationship between type and categories...
Down here is my code snippet on the create form...
<select class="form-control select-picker" name="categories[]" multiple="multiple" title="Choose one or more">
#foreach ($types as $type)
<optgroup label="{{ $type->name}}">
<?php $type_categories = $type->categories;?>
#foreach ($type_categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</optgroup>
#endforeach
Now how can i populated the dropdown in edit mode while marking the selected values removing the optgroup because the code below works if i omit the optgroup
{{ Form::select('categories[]', App::make('Category')->lists('name', 'id'), $school->categories()->select('categories.id AS id')->lists('id'),['class' => 'form-control select-picker','multiple'])}}
You can use custom Form extension for this:
Form::macro('categoriesSelect', function ($name, $types, $selected, $attributes)
{
$groups = [];
foreach ($types as $type)
{
$groups[$type->name] = $type->categories->lists('name', 'id');
}
return Form::select($name, $groups, $selected, $attributes);
});
then just provide a collection of Types with Categories:
Form::categoriesSelect(
'categories[]',
App::make('Type')->with('categories')->get(),
$school->categories()->select('categories.id AS id')->lists('id'),
['class' => 'form-control select-picker','multiple']
)
Note: I wouldn't call those queries in the blade template, but that's another story.

Laravel - Form Input - Multiple select for a one to many relationship

One of the requirements in an application that I am building is for a form input which takes in a varying number of items for a single field. For instance, sports that I play are ('Soccer','Tennis','Croquet').
There are a finite number of sports one can play (arguably), so these items should be selected from a "drop down" type list in the form input.
Downstream of this form will be two tables which have a one-to-many relationship. So from the above, the "user" table would have a single row, while the "user_sports" table would have three rows. These would then be linked by the id field in the user table.
I have not been able to find the sort of functionality where this can be achieved in the documentation (perhaps I am not searching for the correct thing). Below was the closest that I found, but is only for selecting a single item from a drop down list.
http://laravel.com/docs/html#drop-down-lists
Is there a workaround out there that will enable me to get this form element up and running using the Laravel framework?
Alternatively, are there other ways that this sort of functionality can be achieved, without damaging the user experience?
I agree with user3158900, and I only differ slightly in the way I use it:
{{Form::label('sports', 'Sports')}}
{{Form::select('sports',$aSports,null,array('multiple'=>'multiple','name'=>'sports[]'))}}
However, in my experience the 3rd parameter of the select is a string only, so for repopulating data for a multi-select I have had to do something like this:
<select multiple="multiple" name="sports[]" id="sports">
#foreach($aSports as $aKey => $aSport)
#foreach($aItem->sports as $aItemKey => $aItemSport)
<option value="{{$aKey}}" #if($aKey == $aItemKey)selected="selected"#endif>{{$aSport}}</option>
#endforeach
#endforeach
</select>
#SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection.
Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
Laravel 4.2
#SamMonk gave the best alternative, I followed his example and build the final piece of code
<select class="chosen-select" multiple="multiple" name="places[]" id="places">
#foreach($places as $place)
<option value="{{$place->id}}" #foreach($job->places as $p) #if($place->id == $p->id)selected="selected"#endif #endforeach>{{$place->name}}</option>
#endforeach
</select>
In my project I'm going to have many table relationships like this so I wrote an extension to keep it clean. To load it, put it in some configuration file like "app/start/global.php". I've created a file "macros.php" under "app/" directory and included it in the EOF of global.php
// app/start/global.php
require app_path().'/macros.php';
// macros.php
Form::macro("chosen", function($name, $defaults = array(), $selected = array(), $options = array()){
// For empty Input::old($name) session, $selected is an empty string
if(!$selected) $selected = array();
$opts = array(
'class' => 'chosen-select',
'id' => $name,
'name' => $name . '[]',
'multiple' => true
);
$options = array_merge($opts, $options);
$attributes = HTML::attributes($options);
// need an empty array to send if all values are unselected
$ret = '<input type="hidden" name="' . HTML::entities($name) . '[]">';
$ret .= '<select ' . $attributes . '>';
foreach($defaults as $def) {
$ret .= '<option value="' . $def->id . '"';
foreach($selected as $p) {
// session array or passed stdClass obj
$current = #$p->id ? $p->id: $p;
if($def->id == $current) {
$ret .= ' selected="selected"';
}
}
$ret .= '>' . HTML::entities($def->name) . '</option>';
}
$ret .= '</select>';
return $ret;
});
Usage
List without pre-selected items (create view)
{{ Form::chosen('places', $places, Input::old('places')) }}
Preselections (edit view)
{{ Form::chosen('places', $places, $job->places) }}
Complete usage
{{ Form::chosen('places', $places, $job->places, ['multiple': false, 'title': 'I\'m a selectbox', 'class': 'bootstrap_is_mainstream']) }}
A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..
This might be a better approach than top answer if you need to compare 2 output arrays to each other but use the first array to populate the options.
This is also helpful when you have a non-numeric or offset index (key) in your array.
<select name="roles[]" multiple>
#foreach($roles as $key => $value)
<option value="{{$key}}" #if(in_array($value, $compare_roles))selected="selected"#endif>
{{$value}}
</option>
#endforeach
</select>
My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating #foreach but now work with a double #foreach and double #if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
#foreach($tags as $id => $name)
#if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
#foreach (Request::old('tag_id') as $idold)
#if($idold==$id)
selected
#endif
#endforeach
style="padding:5px;">{{ $name }}</option>
#else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
#endif
#endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn´t need this code to work)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
#foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**#if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
#endif**>
{{ ucfirst($categoryType->title) }}</option>
#endforeach
</select>

Laravel fill option values

I'm currently working on a project with a search function. I'm getting some data from my database. I bind this data through my controller. And fill my dropdownlist with it, including a default select item. Is it possible to set the values from the select to the data I retrieve from my database?
// Browser
<select id="game_kind" name="game_kind">
<option value="" selected="selected">Make your choice..</option>
<option value="1">puzzle</option>
<option value="4">dice game</option>
<option value="5">card game</option>
<option value="6">board game</option>
</select>
// Controller
public function Filter()
{
$game_kinds = GameKind::where('game_kind_name_en','!=','')->lists('game_kind_name_en');
return View::make('web.spelzoeken', compact('game_kinds');
}
// View
{{ Form::open(['route' => 'web.search.post']), PHP_EOL }}
{{ Form::label('game_kind',Lang::get('web-zoeken.search-game'))}}
{{ Form::select('game_kind', ['' => Lang::get('web-zoeken.search-option')] + $game_kinds)}}
{{ Form::submit(Lang::get('web-zoeken.search-button'), ['class' => 'button tiny']), PHP_EOL }}
{{ Form::close(), PHP_EOL }}
// Result I really want
<select id="game_kind" name="game_kind">
<option value="" selected="selected">Make your choice..</option>
<option value="puzzle">puzzle</option>
<option value="dice game">dice game</option>
<option value="card game">card game</option>
<option value="board game">board game</option>
</select>
Thanks in advance!
Change this:
$game_kinds = GameKind::where('game_kind_name_en','!=','')
->lists('game_kind_name_en');
into this:
// SELECT 'field' AS 'alias' ...
$game_kinds = GameKind::select('game_kind_name_en', 'game_kind_name_en as game_kind_name_en_key')
->where('game_kind_name_en','!=','')
->lists('game_kind_name_en', 'game_kind_name_en_key');
From the docs:
Specifying A Select Clause
$users = DB::table('users')->select('name as user_name')->get();
or ...->lists(...) in your case
And
Retrieving A List Of Column Values
$roles = DB::table('roles')->lists('title');
This method will return
an array of role titles. You may also specify a custom key column for
the returned array:
$roles = DB::table('roles')->lists('title', 'name');
BTW
- Don't use spaces in HTML-attribute names.
Instead of doing:
value="dice game"
Do like:
value="dice_game".

Categories