yassilah / laravel-nova-nested-form

This package allows you to include your nested relationships' forms into a parent form.
240 stars 96 forks source link

Unable to create new records while overriding the indexQuery of a Resource #67

Open mavericksthinker opened 5 years ago

mavericksthinker commented 5 years ago

Hello @yassipad @303K , I am using verison : 2.1 of this package but while creating new records I am getting same error as referenced below. Any Suggestion to fix this will be very helpful.

{
  "messages" :  "The given data was invalid.",
  "errors" : {
    "answers[0][question]" : ["This id may not be associated with this resource."]
    }
}

This is probably caused by this in the answer resource:

BelongsTo::make('Question')
->searchable()
->rules('required'),

Removing that part will allow me to update answers, but when I try to create them I do get another error message (logic):

{
    "message": "SQLSTATE[HY000]: General error: 1364 Field 'question_id' doesn't have a default value (SQL: insert into `answers` (`title`, `value`, `status`, `follow_up`, `updated_at`, `created_at`) values (dd, aa, 0, 1, 2019-04-25 07:16:35, 2019-04-25 07:16:35))",
    "exception": "Illuminate\\Database\\QueryException",
    "file": "/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php",
    "line": 664,
    ...
}

So instead of removing that part from the answer resource, I've added something:

BelongsTo::make('Question')
->searchable()
->rules('required')
->hideWhenUpdating(),

This again allows me to update Answers, but once I want to add a new one I get the first error message again (logic):

{
  "messages" :  "The given data was invalid.",
  "errors" : {
    "answers[0][question]" : ["This area id may not be associated with this resource."]
    }
}

And I did try some more, but I'm always stuck at not being able to create a new answer. And also the above solutions are not feasible since you will remove the ability to create / update answers by "the normal Nova way"

Originally posted by @davidbonting in https://github.com/yassipad/laravel-nova-nested-form/issues/41#issuecomment-486551812

davidbonting commented 5 years ago

Why did you close it? Do you have a solution?

mavericksthinker commented 5 years ago

As I was overriding the indexQuery of my resource, was getting this error once I commented it out, worked fine. But a way to make this work while overriding the query will be helpful. Currently trying to make a way , but any help will be appreciated.

TheDeadCode commented 5 years ago

+1

davidbonting commented 5 years ago

So in March 2019 I opened an issue #41

Although some suggestions and fixes were provided. It never worked out for me. Even this issue was created months later describing the same issue.

Long story short, but the project were I used to work on and was using this package was on hold until now. So almost half a year later I expected to update this package and all my problems would be resolved. Yet did didn't happen.

With the latest version, the fields aren't even showing ( #66). So I downgraded to 2.0.7.

But I was still stuck with my issue. So I tried a more dirty fix, instead of trying to update this package (because it does works for some users, yet it doesn't for some I'm not comfortable enough to update the fundamentals of this package).

For all who are still experience this issue, let me explain my fix (you may want to checkout the code I shared in #41)

So I have a question, with multiple answers. And it seems like that a BelongsTo field is ignored by this package:

Answer.php

           BelongsTo::make('Question')
            ->searchable()
            ->rules('required'),

That's why my the 'question' field is never displayed / send in the nested form. So by manually adding the 'question' field (/input) to the nested answers and assign the right question id to it. It does work.

Question.php

            NestedForm::make("Answers")->open(true)->beforeFill(function ($request, $model) {
                // $request['answers'] contains the nested form fields (but in my case only the fields: title, value, status. So not the question field that is actually defined in Answers.php BelongTo
                $request['answers'] = collect($request->answers)->map(function($answer) use ($model){
                    // loop over the answers, and assign the question field manually ($model is my Question model in this case)
                    $answer['question'] = $model->id;
                    return $answer;
                });
            }),
mavericksthinker commented 5 years ago

@davidbonting If you are having issues displaying the fields of the nested form with nova v2.0.8 and above you can fork the repo and do the following changes in src/NestedForm.php

  public function jsonSerialize()
    {
        return array_merge([
         >  'panel' => $this->panel,
            'component' => $this->component,
            'prefixComponent' => true,
            'resourceName' => $this->resourceName,

And I did some changes that suits my need and it works like charm. Hope this helps you if you are unable to use updated nova package.

BobbyBorisov commented 5 years ago

@mavericksthinker I am using Nova 2.3 and it does not work unfortunately. did you update as well?

mavericksthinker commented 5 years ago

@BobbyBorisov I am using Nova 2.3 and it works fine for me. Actually its better to fork the repo and apply the fix I gave or the much efficient way will be to not override the jsonSerialize() rather pass the other necessary param in conjunction with other custom functions like

/**
     * Set the viaResource information as meta.
     *
     * @param Model $resource
     *
     * @return self
     */
    protected function setViaResourceInformation(Model $resource)
    {
        return $this->withMeta([
            'viaResource' => Nova::resourceForModel($resource)::uriKey(),
            'viaResourceId' => $resource->id,
            'INDEX' => self::INDEX,
            'ATTRIBUTE' => self::ATTRIBUTE,
            'ID' => self::ID,
        ]);
    }

Just as an example. This will help to avoid breaking the package on subsequent Nova updates. I used the second method. Hope that works out for you.

BobbyBorisov commented 5 years ago

@mavericksthinker I created small question, answer, categories form for just testing the new version and when i submit the form with 1 question 1 answer and 1 category it works but when i create a question with 2 answers and both has 1 category it says "{"message":"The given data was invalid.","errors":{"answers[1][answer]":["The answer field is required."]}}" i am kinda clueless of how to fix this.

just for clarification: question has many answers, answer has many categories. i got 2 nested forms in questions. 1 for answers and answer resource has 1 for categories.

mavericksthinker commented 5 years ago

@BobbyBorisov It will be helpful if you can post the sample code to look upon please also add the relationship functions as it might also be necessary for analysis as the function name also matters.

BobbyBorisov commented 5 years ago

@mavericksthinker hey I just opened a issue, so you can take a look. Its the latest one a.k.a. #81

BobbyBorisov commented 5 years ago

@mavericksthinker hey man, did you manage to look into the my opened issue? I would appreciate it if you have time. Cheers