orlyapps / nova-belongsto-depend

Larave Nova BelongsTo Field with Dependcy
MIT License
182 stars 65 forks source link

Custom Title Field #51

Open codebykyle opened 4 years ago

codebykyle commented 4 years ago

Hello, Thanks for the package. This is very helpful. I had some trouble getting the title property to work. A few of the models I'm using need a particular title depending on the situation.

I just wanted to quickly share two of my solutions for this. You could also use an attribute on the model, per #11, but I wanted to use the Nova resource's title method.

            NovaBelongsToDepend::make('Model', 'relationship, Resource::class)
                ->options(\App\Model::query()->get([
                    'id',
                    'title',
                    'program_type'
                ])->map(function ($item) {
                    $item->setAttribute('calculated_title', (new Resource($item))->title());
                    return $item;
                }))
                ->withMeta(['titleKey' => 'calculated_title']),

This sets a temporary field on the model for calculated_title.

Additionally, you can change the title key with withMeta, like:

            NovaBelongsToDepend::make('Model', 'relationship, Resource::class)
                ->options(\App\Model::query()->get([
                    'id',
                    'title',
                    'program_type'
                ])
                ->withMeta(['titleKey' => 'name']),

Is it possible to maybe expose the title key via a method to make this more formalized rather than going through withMeta?

thaifani commented 4 years ago

not work resource not have map function

vincenzoraco commented 4 years ago

To customise my name property I do this:

->optionsResolve(function ( $model ) {
    return $model->relation1->relation2->map(function ($item) {
        return collect([
            'id' => $item->id,
            'name' => $item->formatted_name,
        ]);
    });
})
->withMeta(['titleKey' => 'name'])

I know it's pretty generic but I hope this helps someone in the same position I was.