Crud: [4.1] InlineCreate Select2 relation fails to create

Created on 7 May 2020  路  4Comments  路  Source: Laravel-Backpack/CRUD

Bug report

What I did

I have a select2 field in my entity with relations to other entity with belongsToMany type of relation. When I try to select an option in select2 and save it, it fails:

exception: "ErrorException"
file: "...\vendor\backpack\crud\src\app\Library\CrudPanel\Traits\Create.php"
line: 121
message: "Invalid argument supplied for foreach()"

What I expected to happen

It should properly save the form

What happened

Exception above

What I've already tried to fix it

Fix could be to add another check for $values in syncPivot method before inner foreach is called:

if (!is_array($values)) {
    $values = [$values];
}

Foreach expects $values to be an array but select2 returns scalar.

Backpack, Laravel, PHP, DB version

When I run php artisan backpack:version the output is:

PHP VERSION:

PHP 7.4.4 (cli) (built: Mar 17 2020 13:49:19) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Xdebug v2.8.1, Copyright (c) 2002-2019, by Derick Rethans

LARAVEL VERSION:

v7.10.3@6e927e78aafd578d59c99608e7f0e23a5f7bfc5a

BACKPACK VERSION:

4.1.x-dev@d0612499fa22d91f7302594313c60880c41c1180

question

All 4 comments

Hello @warton

A select2 field should not be used with belongsToMany, you should use select2_multiple.

But .. as it is a relation you probably safe with CRUD::addField('relation_name_here') of course you can add your own stuff:

CRUD::addField([
'name' => 'relation_name',
'label' => 'your_label'
]);

I don't think this is a bug, let me know how it goes so i can close this.

Well, yes, you are right. It works fine with select2_multiple.

However in my case, this is kind of special situation. Even my relation is BelongsToMany, in the end user can choose only one option for that particular record. So select2_multiple is not a way for me.

Hum .... if user can select only one it might be better to change your database schema and use the BelongsTo, because using a pivot to store only one item per relation seems counter producent.

You can try with: multiple => false in your select2_multiple field definition.

Going to close this as I think it's not a bug.

Let me know if I was wrong.

Best,
Pedro

Ok, it works with your suggestion. You're free to close it.

Thank you for your help :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

genesiscz picture genesiscz  路  3Comments

sseggio picture sseggio  路  3Comments

jorgepires picture jorgepires  路  3Comments

mklahorst picture mklahorst  路  3Comments

sonoftheweb picture sonoftheweb  路  3Comments