Benjacho / belongs-to-many-field-nova

Belongs To Many field Laravel nova to represent many to many relationship in field.
MIT License
157 stars 81 forks source link

Closure for the option method #13

Closed timcv closed 5 years ago

timcv commented 5 years ago

Hello,

Would it be possible to add the possibility for the ->options method to take a closure as argument?

->options(function() {
    \App\Role::all()
})

When doing like this ->options(\App\Role::all()) the field generates one query per row.

Do you think it would be possible to cache it by using a closure?

//Tim

Benjacho commented 5 years ago

Yes it is possible you can make a PR or propose!

timcv commented 5 years ago

I sorry i made a misstake.

What i would want to to is be able to skip the ->options() call all together.

It should be possible to call ::all() on the class i enter as an argument to the ::make() method.

//Tim

timcv commented 5 years ago

I gave it a try but could not come up with with a solution...

I have an idea and that would be to ajax load the options on the details page, but i could not figure out how to get it working...

//Tim

Benjacho commented 5 years ago

Hello timcv i'll do my best to get this working!

timcv commented 5 years ago

Hi, i have worked a bit on another field for a private field.

A good solution would be to skip the options method and user the arguments from the ::make method to create an ajax request and fetch the data that way :)

I got the ide by reading the source code of https://github.com/dillingham/nova-attach-many .

//Tim

Benjacho commented 5 years ago

Yes that's a good idea, basically this options method is different because it allows you to subquery! But function options can override the default Ajax load

timcv commented 5 years ago

Thats sounds even better!

goldmerc commented 4 years ago

Hello @Benjacho - Thanks for a great package!

I'm having trouble setting the options using the options method. I want to set them to avoid the ajax loading time when there are lots of options.

BelongsToManyField::make('Towns')->options(function () {
    return Town::select('id', 'name')
        ->get()
        ->map(function ($item, $key) {
            return [
                'id' => $item->id,
                'name' => $item->name,
                'value' => $item->id,
            ];
        })->values();
}),

But I get no options in the dropdown. Can you explain to me how to use this method properly? Thanks.

goldmerc commented 4 years ago

I just figured out the problem was the anonymous function. Also I was over complicating the code. This seems to work nicely...

            BelongsToManyField::make('Towns')
                ->options(
                    DB::table('silverware_towns')
                    ->select('id', 'name')
                    ->get()
                    ->values()
                ),

Thanks again for a great package