Last active
January 8, 2018 12:32
-
-
Save marekmurawski/8855132 to your computer and use it in GitHub Desktop.
Laravel macro Form::select() with optgroup based on Collection field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// You can put this code into /app/routes.php for testing | |
/* | |
* Form::selectOpt() | |
* | |
* Parameters: | |
* $collection A I\S\Collection instance | |
* $name The HTML "name" | |
* $groupBy Field by which options are grouped | |
* $labelBy Field to use as an option label (default="name") | |
* $valueBy Field to use as option's value (default="id") | |
* $value Value of selected item or items | |
* $attributes An array of additional HTML attributes | |
*/ | |
Form::macro('selectOpt', function(ArrayAccess $collection, $name, $groupBy, $labelBy = 'name', $valueBy = 'id', $value = null, $attributes = array()) { | |
$select_optgroup_arr = []; | |
foreach ($collection as $item) | |
{ | |
$select_optgroup_arr[$item->$groupBy][$item->$valueBy] = $item->$labelBy; | |
} | |
return Form::select($name, $select_optgroup_arr, $value, $attributes); | |
}); | |
/* | |
* Form::selectOptMulti() | |
* | |
* A shortcut for Form::selectOpt with multiple selection | |
*/ | |
Form::macro('selectOptMulti', function(ArrayAccess $collection, $name, $groupBy, $labelBy = 'name', $valueBy = 'id', $value = null, $attributes = array()) { | |
$attributes = array_merge($attributes, ['multiple' => true]); | |
return Form::selectOpt($collection, $name, $groupBy, $labelBy, $valueBy, $value, $attributes); | |
}); | |
/* | |
* Test route | |
* | |
* Assumption: | |
* | |
* Product Model has "id", "name", and "category" fields | |
* | |
* Options will be grouped by "category" field | |
*/ | |
Route::get('selectopt', function() { | |
return Form::selectOpt(Product::all(), 'product_id', 'category', 'name', 'id'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment