Hello,
I have a mysql database with 2 tables (products
and manufacturers
) and I want to assign manufacturers
via select field on my product
blueprint.
Manufactures in the blueprint are loaded as follows:
Product blueprint:
fields:
manufacturer:
type: select
options: query
query:
fetch: page.getManufacturers
text: "{{arrayItem.title}}"
value: "{{arrayItem.id}}"
Model:
public function getManufacturers()
{
$data = Db::select('manufacturers', ['id','title']);
$manufacturers = $data->toArray();
return array_map(function($manufacturer) {
return (object) $manufacturer;
}, $manufacturers);
}
I can create and edit products with the code above and the database is updated as expected. Except the manufacturer select box is not selected anymore when I open the blueprint again to edit an entry and I don’t know how to get the option selected
in my bluerpint. Any ideas?
Could you post your page model where the children are defined?
Yes, of course! It’s taken from the guide Content from a database.
class ManufacturersPage extends Kirby\Cms\Page
{
public function children()
{
$manufacturers = [];
foreach (Db::select('manufacturers') as $manufacturer) {
$manufacturers[] = [
'slug' => $manufacturer->slug(),
'num' => $manufacturer->status() === 'listed' ? 0 : null,
'template' => 'manufacturer',
'model' => 'manufacturer',
'content' => [
'title' => $manufacturer->title() ?? 'New manufacturer',
'text' => $manufacturer->text(),
'status' => is_null($manufacturer->status()) ? 'draft' : $manufacturer->status()
]
];
}
return Pages::factory($manufacturers, $this);
}
}
You don’t assign the manufacturer field in your model, no value, nothing selected.
'content' => [
'title' => $manufacturer->title() ?? 'New manufacturer',
'text' => $manufacturer->text(),
'status' => is_null($manufacturer->status()) ? 'draft' : $manufacturer->status(),
'manufacturer' => 'Your value here',
]
Sorry, I posted the wrong model (manufacturer
model instead of product
model).
I assign the manufacturer field correctly.
But your answer helped to look for the bug in the right place.
The database field of manufacurer was INT instead of VARCHAR. This is where it broke.
Thank you very much for help.