nova-multiselect-field
nova-multiselect-field copied to clipboard
How to replicate with relationship?
I have a resource called Product
and it has a relationship with another named Section
.
Section
is multiple select options of Product whenever I create or update Product.
Now, Whenever I replicate Product
I want it also to replicate Section
(auto select Section like the one replicated).
I have a workaround like this. It seems to work but I'm not so sure.
Does Nova or this package support a way to do it?
Thanks for your help!
public function fields(NovaRequest $request): array
{
return [
//..
$this->sections(),
];
}
public function replicate()
{
$productId = request()->get('fromResourceId');
$sections = \App\Models\ServiceSection::whereHas('products', function(Builder $q) use ($productId) {
$q->where('product_id', $productId);
})->get();
if (!empty($sections)){
self::$isReplicate = true;
$sections->map(function ($section) {
self::$sectionOptions[] = [$section->id];
});
}
return parent::replicate();
}
/**
* @throws Exception
*/
protected function sections(): Multiselect
{
$sections = MultiTagField::make(__('Service Sections'), 'sections')
->api('/api/sections-by-service', ServiceSection::class)
->belongsToMany(ServiceSection::class, false)
->hideFromIndex();
if (self::$isReplicate){
$sections->withMeta(['value' => self::$sectionOptions]);
}
return $sections;
}