Open AforDesign opened 2 years ago
I've found a workaround. When you add the optionsLabel method, the title function is no longer used as id when saving. The title function is still used for display in the field's selection list, but you're limited to a single attribute-name for the display of the selected models. Also the hideSelected functionality will fail, as the title and label differ.
However, it is still possible to use a custom label. Here's what I did to make this possible:
In the related BelongsTo model:
Add a name for a custom attribute to the appends array:
protected $appends = [
'yourAttributeName'
];
Create an accessor for this attribute:
public function getYourAttributeNameAttribute()
{
// return the custom label, in my case:
return $this->id . ':: ' . $this->name;
}
In the Nova Resource, add the optionsLabel method:
BelongsToManyField::make('Products', 'products', Product::class)
->optionsLabel('yourAttributeName'),
In the related BelongsTo Resource (Optional): edit the title function for consistency
public function title() {
return $this->IdName;
}
In my BelongsToMany resource I'm using a custom title for display: public function title() { return $this->id . ':: ' . $this->name; }
This is used for easier identification in several relations and displays just fine. also in the BelongsToManyField. However on Saving, it tries to store this title as foreign key, resulting in an error.
Nova's own BelongsToMany field works fine with the custom title. It attaches without problem.