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()"
It should properly save the form
Exception above
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.
When I run php artisan backpack:version the output is:
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
v7.10.3@6e927e78aafd578d59c99608e7f0e23a5f7bfc5a
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 :)