Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4.1.0][Bug] Problems with relationship field type #2597

Closed
DanielKimmich opened this issue Mar 24, 2020 · 12 comments
Closed

[4.1.0][Bug] Problems with relationship field type #2597

DanielKimmich opened this issue Mar 24, 2020 · 12 comments
Assignees
Labels

Comments

@DanielKimmich
Copy link

DanielKimmich commented Mar 24, 2020

I have the following controller and model

class BlogPostCrudController extends CrudController
{  use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
…
}
class BlogCategoryCrudController extends CrudController
{     use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;
…
}
class BlogPost extends Model
{     use CrudTrait;
protected $fillable = ['title', 'description', 'body', 'featured_image', 'slug', 'category_id', 'author_id', 'posted_at', 'status'];
public function blogcategory()
    {     return $this->belongsTo('App\Models\BlogCategory','category_id', 'id');    }
…
}
class BlogCategory extends Model
{     use CrudTrait;
protected $fillable = ['name', 'description','slug'];
     public function posts()
    {   return $this->hasMany('App\Models\BlogPost','category_id', 'id');     }
….
}

Bug report (first error)

ERROR 500
It's not you, it's me.
Sorry, you can't have two filters with the same name.

What I did

In controller i have define a custom filter

class BlogCategoryCrudController extends CrudController
{     use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation;

   // daterange filter
        $this->crud->addFilter([
            'name'  => 'updated_from_to',
            'label' => trans('common.updated_range'),
            'type'  => 'date_range',
            ],
            false,
            function ($value) { // if the filter is active, apply these constraints
                $dates = json_decode($value);
                $this->crud->addClause('where', 'updated_at', '>=', $dates->from);
                $this->crud->addClause('where', 'updated_at', '<=', $dates->to . ' 23:59:59');
            });
}

Bug report (second error)

I wild create a new post and the category is empty.

What I did

class BlogPostCrudController extends CrudController
{  use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

        $this->crud->addField([    // Relationship
            'name'      => 'category_id',
            'label'     => 'Relationship (no AJAX) <span class="badge badge-warning">New in 4.1</span>',
            'type'      => 'relationship',
            'tab'   => trans('blog.data'),
            'wrapperAttributes' => ['class' => 'form-group col-md-6'],           
            'entity'    => 'blogcategory',
            'attribute' => 'name',
            'model'     => 'App\Models\BlogCategory',
            'ajax' => false,
            'inline_create' => true, // TODO: make this work
         ]);
}

if delete a field attibute 'inline_create',

if you remove the field attribute 'inline_create' then the data is displayed

Bug report (third error)

Facade\Ignition\Exceptions\ViewException
Route [category-inline-create-save] not defined. (View: C:\laragon\www\crudContact\vendor\backpack\crud\src\resources\views\crud\fields\relationship\fetch_or_create.blade.php)
http://crudcontact.telecom.int/admin/blogpost/create

What I did

This occurs when I define the controller name other than entity name. I have defined the attributes in the field, but do not consider.

class BlogPostCrudController extends CrudController
{  use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

        $this->crud->addField([    // Relationship
            'name'      => 'category_id',
            'label'     => 'Relationship (no AJAX) <span class="badge badge-warning">New in 4.1</span>',
            'type'      => 'relationship',
            'tab'   => trans('blog.data'),
            'wrapperAttributes' => ['class' => 'form-group col-md-6'],           
            'entity'    => 'category',
            'attribute' => 'name',
            'model'     => 'App\Models\BlogCategory',
            'ajax' => false,
           'inline_create' => [ 
                'entity' => 'category', // the entity in singular
                'force_select' => true, // should the inline-created entry be immediately selected?
                'modal_class' => 'modal-dialog modal-xl', // use modal-sm, modal-lg modal-xl
                'modal_route' => route('blogcategory-inline-create'), // InlineCreate::getInlineCreateModal()
                'create_route' => route('**blogcategory-inline-create-save**'), // InlineCreate::storeInlineCreate()
                ],              
        ]);
}
class BlogPost extends Model
{     use CrudTrait;
protected $fillable = ['title', 'description', 'body', 'featured_image', 'slug', 'category_id', 'author_id', 'posted_at', 'status'];
public function category()
    {     return $this->belongsTo('App\Models\BlogCategory','category_id', 'id');    }
…
}

Bug report (fourth error)

Facade\Ignition\Exceptions\ViewException
Method Illuminate\Support\Collection::orderBy does not exist. (View: C:\laragon\www\crudContact\vendor\backpack\crud\src\resources\views\crud\fields\relationship\relationship_select.blade.php)
http://crudcontact.telecom.int/admin/blogpost/create

What I did

I want to sort by name
{  use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
…
        $this->crud->addField([    // Relationship
            'name'      => 'category_id',
            'label'     => 'Relationship (no AJAX) <span class="badge badge-warning">New in 4.1</span>',
            'type'      => 'relationship',
            'tab'   => trans('blog.data'),
            'wrapperAttributes' => ['class' => 'form-group col-md-6'],           
            'entity'    => 'category',
            'attribute' => 'name',
            'model'     => 'App\Models\BlogCategory',
            'options'   => (function ($query) {
               return $query->orderBy('name', 'ASC')->get(); }), 
            'ajax' => false,
        ]);
}

Thank you in advance for helping me. I don't know if there are any bugs.

Backpack, Laravel, PHP, DB version

PHP VERSION:

PHP 7.2.11 (cli) (built: Oct 10 2018 02:04:07) ( ZTS MSVC15 (Visual C++ 2017) x64 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

LARAVEL VERSION:

v6.18.3@4e48acfaba87f08320a2764d36c3b6a4a4112ccf

BACKPACK VERSION:

4.1.x-dev@3eee77d99d429e257c4168071e70d8e1f5b92fec

@DanielKimmich
Copy link
Author

Add a image
Empty select
image

Display a data in select
image

@tabacitu tabacitu changed the title Problems with relationship field type [4.1.0][Bug] Problems with relationship field type Mar 26, 2020
@tabacitu tabacitu added the Bug label Mar 26, 2020
@tabacitu
Copy link
Member

Thank you for taking the time to test and submit this @DanielKimmich ! This feature is @pxpm 's baby - so I'll let him investigate and respond/fix. Cheers!

@pxpm
Copy link
Contributor

pxpm commented Apr 7, 2020

Thank you @DanielKimmich for raising this issues.

I see one is not related with fields, but with filters. On the other hand, I spot another place where you probably forget to add the fetchOperation. And last, relationship only work when you provide a relation as a name. No need to provide name => category_id in a belongsTo, just provide the name => category if category is the model function returning the relation.

This feature has received some updates in the latest days. There is also an small guide (still WIP) on this operation https://backpackforlaravel.com/docs/4.1/crud-operation-inline-create

This is a bit confusing to have issues like this, so i am going to close this.

If you find another issue, please open a new issue explaining what you are trying to achieve and what went wrong. But keep in mind that probably you should ask first in some other mediums like gitter or stackoverflow, because like I said, sometimes is implementation error, or bad documentation from our side, and we avoid polluting git with non-bugs.

Best,

@DanielKimmich
Copy link
Author

I was able to solve two points

###this error:
Facade\Ignition\Exceptions\ViewException
Route [category-inline-create-save] not defined. (View: C:\laragon\www\crudContact\vendor\backpack\crud\src\resources\views\crud\fields\relationship\fetch_or_create.blade.php)

replacing the following code

        //route to create a new entity
        $field['inline_create']['create_route'] = $field['inline_create']['create_route'] ?? route($field['inline_create']['entity']."-inline-create-save");

        //route to modal
        $field['inline_create']['modal_route'] = $field['inline_create']['modal_route'] ?? route($field['inline_create']['entity']."-inline-create");

###this error: #2654
Facade\Ignition\Exceptions\ViewException
Method Illuminate\Support\Collection::orderBy does not exist. (View: C:\laragon\www\crudContact\vendor\backpack\crud\src\resources\views\crud\fields\relationship\relationship_select.blade.php)

replacing the following code
$field['options'] = call_user_func($field['options'], $field['model']::query())->pluck($field['attribute'],$connected_entity_key_name);

@pxpm
Copy link
Contributor

pxpm commented Apr 9, 2020

Thank you very much @DanielKimmich

The second issue already has a PR, do you want to submit a PR with your fix to the first issue, or should I do it ?

Best,
Pedro

@DanielKimmich
Copy link
Author

I summarize as I solved, using the following code:

class BlogPostCrudController extends CrudController
{   use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

        $this->crud->addField([    // Relationship
            'name'      => 'category_id',
            'label'     => trans('blog.post.category') .'<span class="badge badge-warning"> New in 4.1</span>',
            'type'      => 'relationship',
            'tab'   => trans('blog.data'),
            'wrapperAttributes' => ['class' => 'form-group col-md-6'],           
            'entity'    => 'category',
            'attribute' => 'name',
            'model'     => 'App\Models\BlogCategory',
            'options'   => (function ($query) {
                return $query->orderBy('name', 'ASC')->get(); }),
            'ajax' => false,
           'inline_create' => [ 'entity' => 'blogcategory'  ],             
            ]);

   public function fetchCategory()
    {   return $this->fetch('App\Models\BlogCategory');  }
}

The select was empty because it misinterpreted the documentation, in the function it put "return $ this-> fetch (App\Models\BlogCategory:class);" without quotes with the word class.

On the other hand, it is not necessary to modify the function "fetch_or_create.blade.php", since the field "'inline_create' => [ 'entity' => 'blogcategory'] " must be the name of the controller, in my case it is different from the entity in the select.

I don't know how to solve the filter
ERROR 500
It's not you, it's me.
Sorry, you can't have two filters with the same name.

@anovelexperience
Copy link

Hi,

Sorry, I've been bit by this too (automatic button to create related records is a feature I just can't resist). I have the Route [category-inline-create-save] not defined error. Naturally, I don't want to edit anything in my vendor folder. Since this is a view, can it be published and I can override it in my views/vendor folder?

Thanks in advance.

Dracula

@pxpm
Copy link
Contributor

pxpm commented Apr 22, 2020

@anovelexperience Thanks for bring this up.

That error is probably a bad implementation on your side. Bare with me, I said probably :)

If you are willing to join us on https://gitter.im/BackpackForLaravel/Lobby you can share some code and we can see what is missing.

Best,

@tabacitu
Copy link
Member

automatic button to create related records is a feature I just can't resist

🥳 🎉

@tm-blg
Copy link

tm-blg commented Apr 8, 2021

#2
Laravel-Backpack/community-forum#2

dear, Pedro, u need be write only this: add InlineCreateOperation into child Controller.

THANK U SO MUCH!

@pxpm
Copy link
Contributor

pxpm commented Apr 8, 2021

Hello again @tm-blg

Step 1. Use the operation trait on your secondary entity's CrudController (aka. the entity that will gain the ability to be created inline, in our example CategoryCrudController).

And previously in the requirements:

.....

- the main entity would be Article (big form);
- the secondary entity would be Category (small form, in a modal);

It's nice that you found the solution, but in my opinion the docs are very clear when they say to add the trait in the controller of the entity that will gain the ability to be created.

But if you feel I am wrong, and sometimes I am for sure, please open a pull request, so it will be reviewed by other people that might agree with you and it would be merged, no problem.

Wish you the best,
Pedro

@tm-blg
Copy link

tm-blg commented Apr 8, 2021

I think so that I was not attentive. In that article, in the picture above, an example with a demo was considered, if I delved into it well, I would understand who is the parent, who is the child controller.

Everything is complicated by the fact that I am not a native speaker of English, I have to use a translator, which also complicates the perception.

At your discretion, of course, but I would add an explanation about adding InlineCreateOperation to the child.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants