Hey, I might be using this wrong... but I didn't see in documentation where to get this to work.
Documentation: https://laravel-backpack.readme.io/docs/crud-fields#select2_multiple-n-n-relationship
I'm using a custom Pivot Table for many-to-many relationship (https://laravel.com/docs/5.2/eloquent-relationships#many-to-many).
Challenge.php model:
...
public function teams()
{
return $this->belongsToMany('App\Team', 'challenge_team', 'challenge_id', 'team_id')->withTimestamps();
}
...
_ChallengeCrudController.php :_
...
$this->crud->addField(
[ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Teams Involved",
'type' => 'select2_multiple',
'name' => 'teams', // the method that defines the relationship in your Model
'entity' => 'teams', // the method that defines the relationship in your Model
'attribute' => 'team_name', // foreign key attribute that is shown to user
'model' => "App\Team", // foreign key model
'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
]
);
...
Doing this... I was able to select and SAVE NEW Challenges with multiple Teams, but I was unable to EDIT and see the previously selected Teams. It did persist to database... but didn't render them in view properly.
I did the following to make it work:
_ChallengeCrudController.php :_
...
$this->crud->addField(
[ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Teams Involved",
'type' => 'select2_multiple',
'name' => 'teams', // the method that defines the relationship in your Model
'entity' => 'teams', // the method that defines the relationship in your Model
'attribute' => 'team_name', // foreign key attribute that is shown to user
'model' => "App\Team", // foreign key model
'pivot' => true, // on create&update, do you need to add/delete pivot table entries?
'foreign_pivot_key' => 'team_id'
]
);
...
Then added the foreign_pivot_key to select2_multiple.blade.php file:
...
<!-- select2 multiple -->
<div class="form-group">
<label>{{ $field['label'] }}</label>
<?php
$field['foreign_pivot_key'] = !empty($field['foreign_pivot_key']) ? $field['foreign_pivot_key'] : 'id';
?>
<select
class="form-control select2"
@foreach ($field as $attribute => $value)
@if (is_string($attribute))
@if ($attribute=='name')
{{ $attribute }}="{{ $value }}[]"
@else
{{ $attribute }}="{{ $value }}"
@endif
@endif
@endforeach
multiple>
<option value="">-</option>
@if (isset($field['model']))
@foreach ($field['model']::all() as $connected_entity_entry)
<option value="{{ $connected_entity_entry->getKey() }}"
@if ( (isset($field['value']) && in_array($connected_entity_entry->getKey(), $field['value']->lists($field['foreign_pivot_key'])->toArray())) || ( old( $field["name"] ) && in_array($connected_entity_entry->getKey(), old( $field["name"])) ) )
selected
@endif
>{{ $connected_entity_entry->{$field['attribute']} }}</option>
@endforeach
@endif
</select>
</div>
...
Let me know if that's a good work-around.
LOVE THE BACKPACK packages!!!
Hi @BinaryBlock ,
Thank you for the report and solution and sorry to be so late to reply.
I _think_ this condition might work too, with the added benefit of not having to specify the "foreign_pivot_key":
@if ( (isset($field['value']) && in_array($connected_entity_entry->getKey(), $field['value']->lists($connected_entity_entry->getKeyName(), $connected_entity_entry->getKeyName())->toArray())) || ( old( $field["name"] ) && in_array($connected_entity_entry->getKey(), old( $field["name"])) ) )
Basically instead of telling the field what the foreign pivot key is, we get it from the object.
Could you please try it when you have the time and tell me if it works for you too? If so, I'll push the update immediately.
Thank you!
Below is the full modified select2_multiple.blade.php so it's easier for you to test:
<!-- select2 multiple -->
<div @include('crud::inc.field_wrapper_attributes') >
<label>{{ $field['label'] }}</label>
<select
name="{{ $field['name'] }}[]"
@include('crud::inc.field_attributes', ['default_class' => 'form-control select2'])
multiple>
<option value="">-</option>
@if (isset($field['model']))
@foreach ($field['model']::all() as $connected_entity_entry)
<option value="{{ $connected_entity_entry->getKey() }}"
@if ( (isset($field['value']) && in_array($connected_entity_entry->getKey(), $field['value']->lists($connected_entity_entry->getKeyName(), $connected_entity_entry->getKeyName())->toArray())) || ( old( $field["name"] ) && in_array($connected_entity_entry->getKey(), old( $field["name"])) ) )
selected
@endif
>{{ $connected_entity_entry->{$field['attribute']} }}</option>
@endforeach
@endif
</select>
{{-- HINT --}}
@if (isset($field['hint']))
<p class="help-block">{!! $field['hint'] !!}</p>
@endif
</div>
{{-- ########################################## --}}
{{-- Extra CSS and JS for this particular field --}}
{{-- If a field type is shown multiple times on a form, the CSS and JS will only be loaded once --}}
@if ($crud->checkIfFieldIsFirstOfItsType($field, $fields))
{{-- FIELD CSS - will be loaded in the after_styles section --}}
@push('crud_fields_styles')
<!-- include select2 css-->
<link href="{{ asset('vendor/backpack/select2/select2.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('vendor/backpack/select2/select2-bootstrap-dick.css') }}" rel="stylesheet" type="text/css" />
@endpush
{{-- FIELD JS - will be loaded in the after_scripts section --}}
@push('crud_fields_scripts')
<!-- include select2 js-->
<script src="{{ asset('vendor/backpack/select2/select2.js') }}"></script>
<script>
jQuery(document).ready(function($) {
// trigger select2 for each untriggered select2_multiple box
$('.select2').each(function (i, obj) {
if (!$(obj).data("select2"))
{
$(obj).select2();
}
});
});
</script>
@endpush
@endif
{{-- End of Extra CSS and JS --}}
{{-- ########################################## --}}
Could you please try it when you have the time and tell me if it works for you too? If so, I'll push the update immediately.
Ahhh.... you rock!
Yes, it worked great. Smart idea about grabbing pivot info from object.
Push away.

Thank you!
Hi, I have the same problem, but when I make the change you say I throw an error that the method list does not exist, I am using laravel 5.4
Sorry for my english, the blade pluck in my example does not load the data stored in the table when editing
hi,I have same problem, but I use $this->crud->addField() method ,please help

I want show filed to list
and update selected


@LinLin520 shouldn't you alse set pivot => true in field definition ?
@LinLin520 shouldn't you alse set
pivot => truein field definition ?
Thank you ,I've settled it. it's my jonin table mistake
CampaignsCrudController .php
// ------ CRUD FIELDS --- Medias ---
$this->crud->addField([
'name' => "medias",
'label' => "Media Type",
'type' => 'select_multiple',
'entity' => 'medias',
'attribute' => 'name',
'model' => "App\Models\Medias",
'pivot' => true,
]);
// ------ CRUD COLUMNS --- Medias ---
$this->crud->addColumn([
'name' => "medias",
'label' => "Media Type",
'type' => "model_function",
'function_name' => 'getMediaName',
]);
Campaigns.php
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
public function getMediaName()
{
$name = '';
foreach ($this->medias as $val){
$name .= $val->name .',';
}
return substr($name,0,-1);
}
/**
* Get the Media for the Db Medias
*/
public function Medias(){
return $this->belongsToMany('App\Models\Medias','campaign_medias','campaign_id','media_id');
}
list show

@tabacitu Does this works with backpack 3.5? select2_multiple.blade.php doesn't look the same.
It's a nice feature, that I will love to use.
@jrbecart yes, it should work just fine - the fix was pushed back in 2016 ;-) https://github.com/Laravel-Backpack/CRUD/commit/33d41b345439c262bf5832b18ef192ff42f77fe1 You can use any primary key column you want, 'id' is no longer hardcoded anywhere in Backpack.
Cheers!
Most helpful comment
@LinLin520 shouldn't you alse set
pivot => truein field definition ?