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.
If you would like you would like the
product_SKU,priceandcurrent_stockfields to be completed when someone selects a certainproductinside Orders, you should be able to do that in JS, using the CrudField JS API. You will need: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
relationshipfield, 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:
I would find that more intuitive. And you can achieve that easily, with no custom code, using the
relationshipfield with subfields.Hope it helps!