BackPack框架中repeatable字段内嵌select2_from_array多选数据不回显问题求助
I’ve run into this exact issue before with Backpack’s repeatable fields and multi-select inputs—let’s break down what’s going wrong and how to fix it.
The Core Problem
Looking at your stored data, the key for the range values is range[] instead of just range. When you enable allows_multiple on a select2_from_array field inside a repeatable, Backpack handles the array submission automatically, so you don’t need to append [] to the field name. The mismatch between your field’s name (range) and the stored key (range[]) is why the selected values aren’t being echoed back.
Step-by-Step Fix
Correct the Field Name in Your Controller
Keep the field name asrange(no[]suffix). Backpack will handle the array submission for you whenallows_multipleis set totrue:$this->crud->addField( [ 'name' => 'schedule', 'label' => 'Schedule', 'type' => 'repeatable', 'fields' => [ [ 'name' => 'day', 'label' => 'Day', 'type' => 'select_from_array', 'options' => Day::titles(), 'allows_null' => false, ], [ 'name' => 'range', // Keep this as "range", not "range[]" 'label' => 'Range', 'type' => 'select2_from_array', 'options' => $this->getScheduleRange(), 'default' => $this->getDefaultScheduleRange(), 'allows_null' => false, "allows_multiple" => true, ], ], ] );Fix the Stored Data Structure
Update your database entries to userangeas the key instead ofrange[]. Your stored JSON should look like this:[{"day": "1", "range": ["0", "1"]}]This matches the field name you defined, so Backpack can map the stored values back to the select2 options correctly.
Verify Your Options Array
Make sure$this->getScheduleRange()returns a proper key-value array (where the keys match the stored values). For example:private function getScheduleRange() { return [ '0' => '1:30:00 - 2:00:00', '1' => '2:30:00 - 3:00:00', // ... other options ]; }This ensures that the stored values (
"0","1") correspond to the correct option labels in the select2 dropdown.
Why This Works
Backpack’s repeatable field wraps nested fields in an array context automatically. When you enable allows_multiple on the select2_from_array field, it expects the stored data to be an array under the field’s exact name (not name[]). By aligning the field name, stored data key, and options array structure, the select2 component will correctly recognize and display the selected values.
内容的提问来源于stack exchange,提问作者iron-viper

