How to get two fields or more as attributes in relations in Laravel Backpack

68 views Asked by At

I have database with the structure:

products(id, name, description, SKU, price, current_stock) <br/>
orders(id, date,name, description, product_SKU, price, current_stock)

In Order controller I have

CRUD::field([
    'type'=>'select2',
    'name'=>'product_name',
    'label'=>'Product Name',
    'model'=>'App\Models\Products',
    'attribute'=>'name',
    'allows_null'=>true,
    'entity'=>'productrelation',
]);

CRUD::field([
    'type'=>'text',
    'name'=>'product_sku',
    'label'=>'Product SKU',
    'attributes' => [
        'readonly' => true,
    ],
    'entity' => 'productrelation',
    'attribute' => 'sku',
    'depends_on' => [
        'product_name' => '!=null',
    ],
    'value' => function($crud) {
        $product= \App\Models\Products::where('product_name', $crud->getRequest()->input('product_name'))->first();
        return $product ? $product->sku : '';
    }
]);

When the product name is selected the fields product_SKU, price and current_stock should be populated with the data from the products db (this fields are readonly). The product_name field works fine showing all the product names, but the problem is that I don't know how to populate the other fields. I tried setting the value to a function that should retrieve the product_sku based on the product_name selected (I think it's kind of correct) but it doesn't retrieve a string and it throws an error.

1

There are 1 answers

0
tabacitu On

If you would like you would like the product_SKU, price and current_stock fields to be completed when someone selects a certain product inside Orders, you should be able to do that in JS, using the CrudField JS API. You will need:

  • an API to respond to requests
  • a bit of JS that sends a call to that API to get the correct info
  • a bit of JS that sets those values on the "dummy inputs" (here is where you would use the CrudField JS API)

Take a look at the step-by-step guide.


As a personal opinion... for a relationship like yours, I would not use custom fields like that, but the relationship field, which also allows for subfields.

To rephrase: if one Order can have multiple Products, when I open an "order form" I expect to be able to... select multiple products. Like it's done in the Backpack online demo for Invoices: enter image description here

I would find that more intuitive. And you can achieve that easily, with no custom code, using the relationship field with subfields.

Hope it helps!