添加到购物车按钮 Yii2
我想制作一个按钮,按下该按钮时将数据插入表名“cart”中 这是我在索引中的按钮
'cart' => function ($url, $model, $key) {
$modelId = $model->id;
return Html::button('<i class="fas fa-shopping-cart"></i>',
[
'class' => 'btn btn-xs btn-outline-success',
'style' => 'width:80px; margin-top: 5px',
'data-toggle' => 'tooltip',
'title' => Yii::t('app', 'Cart'),
'onClick' => 'addProduct('. "{$modelId}" . ');'
]);
},
这是我的功能
public function addProduct($id)
{
$product = Product::find()->where(['id' => $id])->one();
if (isset($product)) {
Yii::$app->db->createCommand()->insert("cart", [
"product_id" => $product->id,
"name" => $product->name,
"price" => $product->price,
"image" => $product->image,
])->execute();
Yii::$app->session->setFlash('success', 'Item added successfully');
}
}
我有这个错误
未捕获的引用错误:addProduct 未定义 在 HTMLButtonElement.onclick
I want to make a button that when it's pressed insert data into table name 'cart'
This is my button in index
'cart' => function ($url, $model, $key) {
$modelId = $model->id;
return Html::button('<i class="fas fa-shopping-cart"></i>',
[
'class' => 'btn btn-xs btn-outline-success',
'style' => 'width:80px; margin-top: 5px',
'data-toggle' => 'tooltip',
'title' => Yii::t('app', 'Cart'),
'onClick' => 'addProduct('. "{$modelId}" . ');'
]);
},
And this is my function
public function addProduct($id)
{
$product = Product::find()->where(['id' => $id])->one();
if (isset($product)) {
Yii::$app->db->createCommand()->insert("cart", [
"product_id" => $product->id,
"name" => $product->name,
"price" => $product->price,
"image" => $product->image,
])->execute();
Yii::$app->session->setFlash('success', 'Item added successfully');
}
}
And I have this error
Uncaught ReferenceError: addProduct is not defined
at HTMLButtonElement.onclick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
评论需要50声望,所以我发送回复。
如果
public function addProduct
是一个PHP函数,点击事件是javascript事件,也许你必须在页面中编写一个js函数?
就像那里:
function() {alert('按钮被点击!'); });
是js函数。(内联注册脚本)comment need 50 reputation, so I send answer.
if
public function addProduct
is a PHP function,on click event is javascript event, maybe you must write a js function in page?
like there:
the
function() { alert('Button clicked!'); });
is js function.(Registering inline scripts)