'Select2 keep showing "Searching" in ajax with pivot (n-n) in Laravel Backpack 5 Pro

I have 2 models: Order and Product, each has belongsToMany with pivot set properly.

In OrderCrudController, I also use FetchOperation and make a fethProducts() function as below:

use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;

public function fetchProducts()
{
    return $this->fetch([
        'model' => \App\Models\Product::class,
        'searchable_attributes' => ['name','sku']
    ]);
    // return $this->fetch(\App\Models\Product::class); <-- I also tried this one
}

protected function setupCreateOperation()
{
    CRUD::setValidation(OrderRequest::class);
    
    // other fields

    $this->crud->addField([
        'name' => 'products',
        'type' => 'relationship',
        'pivotSelect' => [
            'attribute' => 'name',
            'ajax'      => true,
        ],
        'subfields' => [
            [
                'name' => 'quantity',
                'type' => 'number',
            ],
        ],
    ]);
}

But it comes to unexpected behavior when I search the product, the select2 field remains "searching" though the request successfully retrieved the data.

screenshot - select2 field

screenshot - ajax results

PS: this field works perfectly without subfields, no vendor overrides etc., so I think I've set everything correctly.

Anyone can help?



Solution 1:[1]

I just came accross this exact problem and after quite some research and trials, i finally found a solution !

The problem seems to be related to the relationship field type inside the pivotSelect. Try to use select2_from_ajax instead and don't forget to set method to POST explicitly, that worked for me like a charm.

Here is what you might try in your case :

$this->crud->addField([
    'name' => 'products',
    'type' => 'relationship',
    'pivotSelect' => [
        'attribute' => 'name',
        'type'      => 'select2_from_ajax',
        'method'    => 'POST',
        'data_source' => backpack_url('order/fetch/products') // Assuming this is the URL of the fetch operation
    ],
    'subfields' => [
        [
            'name' => 'quantity',
            'type' => 'number',
        ],
    ],
]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1