Reputation: 57
So I have three models, Product, Sale and Code. Each Product belongs to a Code model (it's similar to a User) and each Sale has a field for the Code who is selling the Product and one for the Code who is buying it. In the Product's list view I want to have a button called 'Sell' that redirects me to the Sale's create view with the Product's Code (basically the owner) passed in it so I can create a Sale with the Product and its Code already inserted.
I followed the documentation (https://backpackforlaravel.com/docs/3.4/crud-buttons) for creating a custom button, but when I get to the part inside the new function (in the guide it's 'moderate', for me it's 'sell') I can't redirect to the create view of the Sale model (the one I get by clicking Create in the Sale's CRUD) created when I ran
php artisan backpack:crud Sale
How can I do this?
N.B.: I already built all the model's relative CRUDs.
Button's code: sell.blade.php
@if($crud->hasAccess('update'))
<a href="{{ url($crud->route.'/'.$entry->getKey().'/sell') }} " class="btn btn-sm btn-link"><i class="las la-dollar-sign"></i>Vendi</a>
@endif
sell
method in the ProductCrudController
public function sell($id) {
// add redirect to Sale's create view with the product's id and owner
}
Sale model
class Sale extends Model {
//
use CrudTrait;
protected $guarded = [];
public function code() {
return $this->belongsToMany('App\Models\Code', 'code', 'code');
}
public function product() {
return $this->belongsTo('App\Models\Products');
}
}
Product model
class Product extends Model {
//
use CrudTrait;
protected $guarded = [];
public function productCode() {
return $this->belongsTo('App\Models\Code', 'code', 'code');
}
public function sales() {
return $this->hasMany('App\Models\Sale');
}
}
Code model
class Code extends Model {
//
use CrudTrait;
protected $guarded = [];
protected $primaryKey = 'code';
protected $keyType = 'string';
public function products() {
return $this->hasMany('App\Models\Product', 'code', 'code');
}
}
Upvotes: 2
Views: 1577
Reputation: 19571
You could do the redirect in a method in the product's crud controller as you've started to, but I would actually do it directly in the button.
In sell.blade.php
I'd do something like:
@if($crud->hasAccess('update'))
<a href="{{ url('admin/sales/create/?code='.$entry->getKey() }} " class="btn btn-sm btn-link"><i class="las la-dollar-sign"></i>Vendi</a>
@endif
Note that assumes the path to your sale crud controller is admin/sales/
, modify that if thats not the case.
Then, in your Sale crud controller where you set up your fields, set the field's default from the GET parameter if present something like:
$this->crud->addField([
'name' => 'code',
'label' => 'Code',
'type' => 'text',
'default' => request()->input('code', ''),
]);
Upvotes: 4