This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Sometimes you want to display a dropdown with more than just the name of the item that can be selected.
For example a standard drop down of cars would be:
- Audi
- Opel
- Mercedes
- Suzuki
But we want to display also the unique sales code of the car.
- Audi (AU)
- Opel (OL)
- Mercedes (ME)
- Suzuki (SU)
There's no default way to combine inputs like that from a different model. So we have to do it ourselves This is the layout I use for this example:
- Model Manager: This holds all the different cars
- Model PriceManager: This holds prices. This is where we want to display a dropdown with cars
In /plugin/carmanager/models/pricemanager/fields.yaml we define the following for car
car :
span: left
type: dropdown
label: Choose
This will make sure the function get*name*Options
gets called.
This function wants a return value in the form of
['key'] => ['value']
Where key
will be the thing that gets saved in the database, and value
the thing that gets displayed.
In this case we need in /plugin/carmanager/models/PriceManager.php
the following function to get the items to display properly.
public function getCarOptions() {
$res = Manager::get(['id','name','code'])->toArray();
$ret = [];
foreach($res as $value) {
// Turns it into ['33'] => 'Audio (AU)'
$ret[$value['id']] = $value['name'] . ' ('.$value['code'].')';
}
return $ret;
}
And now you can display the dropdown values the way you want to :-)
Last updated
1-1 of 1