orlyapps / nova-belongsto-depend

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

Fails when table is empty #4

Closed glennwilton closed 6 years ago

glennwilton commented 6 years ago

Narrowed down a problem where the modelKeyName/valueKeys are not set, this causes the dependKey to be missing on the Request to the fieldController, with no key the optionsResolve callback is passed a null not the Selected Model

The problem starts with the resolve function when it trys to get the model from the belongsTo Relationship In the code below

$value = $resource->{$this->attribute}()->withoutGlobalScopes()->first();

If the Table is empty then the $resource has no Attributes.

This is where I'm not that knowledgeable with Laravel, Is it possible to get the attributes and also the belongTo relationship from a Model if the table is Empty? Empty table = no attributes.

glennwilton commented 6 years ago

Fixed it, Rather than loading the first() which does not work, use the getForeignKey() off the BelongsTo Class

Solved a LOT of problems I was having.... Still need to workout a pull request :-)

    public function resolve($resource, $attribute = null)
    {
        parent::resolve($resource, $attribute);

        $this->resourceParentClass = get_class(Nova::newResourceFromModel($resource));

        $foreign = $resource->{$this->attribute}();
        $this->modelKeyName = $foreign->getForeignKey();

        $value = $foreign->withoutGlobalScopes()->first();
        if ($value) {
            $this->valueKey = $value->getKey();
            $this->value = $this->formatDisplayValue($value);
        }

        if ($this->dependsOn) {
            $this->dependKey = $resource->{$this->dependsOn}()->getForeignKey();
        }
    }
orlyapps commented 6 years ago

Hello,

thanks for the fix. I have merged your changes: https://github.com/orlyapps/nova-belongsto-depend/commit/6884f9fdf607e52f6a8e00deb61cfbea97bb3b34

Can you try it again?