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
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:
$this->registerJs(
"$('#myButton').on('click', function() { alert('Button clicked!'); });",
View::POS_READY,
'my-button-handler'
);
the function() { alert('Button clicked!'); }); is js function.(Registering inline scripts)
Related
I'm trying to use the select option to create an event with a Modal with the selected date using Full Calendar - Philippfrenzel but I don't know how.
I already have an event Click which works but that it's not what I really want.
Controller:
public function actionRequisitar(){
$searchModel= new RequisicaoSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$events = [];
foreach(Requisicao::find()->all() as $requisicao){
$event = new \yii2fullcalendar\models\Event();
$event->id = $requisicao->id;
$event->title = $requisicao->motivo_requisicao;
$event->start = $requisicao->data_inicio_req;
$events[] = $event;
}
return $this->render('requisitar',[
'events'=>$events,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionCreate()
{
$model = new Requisicao();
//$model->data_inicio_req=$date;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id, 'utilizador_id' => $model->utilizador_id, 'sala_id' => $model->sala_id]);
}
return $this->renderAjax('create', [
'model' => $model,
]);
}
Index:
<?= \yii2fullcalendar\yii2fullcalendar::widget(array(
'events' => $events,
'id' => 'calendar',
));
?>
Main.js
$(function () {
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
$(document).on('click', '.fc-day', function () {
var date = $(this).attr('data-date');
$.get('index.php?r=requisicao/create', {'date': date}, function (data) {
$('#modal').modal('show')
.find('#modalContent')
.load(data);
});
});
});
Inside the configuration of Index where you setup the fullcalendar widget:
<?= \yii2fullcalendar\yii2fullcalendar::widget(array(
'events' => $events,
'id' => 'calendar',
));
?>
You must add the property eventClick that triggers an JS function once an event is clicked.
You can do it like this:
<?= \yii2fullcalendar\yii2fullcalendar::widget(array(
'events' => $events,
'id' => 'calendar',
'eventClick' => new JsExpression('(event) => handleClick(event)'),
));
?>
Notice that handleClick has to be a real function that is declared in your javascript, you could change handleClick(event) for console.log(event) to check if it is working as you expect before creating the function.
I'm trying to add my own action button in Yii2-Kartik Gridview.
This is my custom button:
This is my code in index.php
[
'class' => 'yii\grid\ActionColumn',
'template' => '{edit}',
'buttons' => [
'edit' => function ($url, $model) {
return Html::a('<button type="button" class="btn btn-edit-npwp"><i class="glyphicon glyphicon-plus-sign"></i></button>', $url, [
'title' => Yii::t('app', 'Edit'),
'data-toggle' => "modal",
'data-target' => "#myModal",
'data-method' => 'post',
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'edit') {
$url = Url::toRoute(['vatout-faktur-out/add-data', 'id' => $model->fakturId], ['data-method' => 'post',]);
return $url;
}
}
],
and this is my action in controller.php
public function actionAddData($id) {
$model = new VatoutFakturOut();
return $this->render('addData', [
'model' => $model,
]);
}
I want to process the data from the row that I've clicked the button.
But, this return error
Missing required parameters: id
Why does this happen? And how to fix this?
Thanks
In urlCreator you used if statement to check, if action is edit, and if it is, you add param id to your button url. Otherwise it doesnt have one, so there's two solutions:
Remove if statement from:
'urlCreator' => function ($action, $model, $key, $index) {
$url = Url::toRoute(['vatout-faktur-out/add-data', 'id' => $model->fakturId]);
return $url;
}
Or remove$id from your actionAddData() - because youre not using it at all:
public function actionAddData() {
$model = new VatoutFakturOut();
return $this->render('addData', [
'model' => $model,
]);
}
new in php and use yii2 as foundation to web development. please help me to simplify this code, im trying to show in popup ActionColumn buttons e.g. view, update and delete buttons. here's my code
'class' => 'yii\grid\ActionColumn',
'buttons'=>[
'view'=>function($url,$model){
return Html::a('<span class="glyphicon glyphicon-eye-open")></span>',$url,['class'=>'view', 'data-pjax'=>0]);
},
'update'=>function($url,$model){
return Html::a('<span class="glyphicon glyphicon-pencil")></span>',$url,['class'=>'update', 'data-pjax'=>0]);
}
],
],
],
]);
$this->registerJs(
"$(document).on('ready pjax:success', function() { // 'pjax:success' use if you have used pjax
$('.view').click(function(e){
e.preventDefault();
$('#pModal').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
});
});
");
Modal::begin([
//'header'=>'<span id="modalHeaderTitle"></span>',
//'headerOptions'=>['id'=>'modalHeader'],
'id'=>'pModal',
'size'=>'modal-lg',
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => FALSE]
]);
echo "<div id='modalContent'></div>";
Modal::end();
$this->registerJs(
"$(document).on('ready pjax:success', function() { // 'pjax:success' use if you have used pjax
$('.update').click(function(e){
e.preventDefault();
$('#qModal').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
});
});
");
Modal::begin([
//'header'=>'<span id="modalHeaderTitle"></span>',
//'headerOptions'=>['id'=>'modalHeader'],
'id'=>'qModal',
'size'=>'modal-lg',
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => FALSE]
]);
echo "<div id='modalContent'></div>";
Modal::end()
?>
please assist me
'buttons'=>[
'view'=>function($url,$model){
return Html::a('<span class="glyphicon glyphicon-eye-open")></span>',$url,['class'=>'view action-btn', 'data-pjax'=>0]);
},
'update'=>function($url,$model){
return Html::a('<span class="glyphicon glyphicon-pencil")></span>',$url,['class'=>'update action-btn', 'data-pjax'=>0]);
}
],
],
],
action-btn added for both button. Now call a ajax from your view and write your modal code in there.
$this->registerJs( "$.ajax({
url: '$url',
type: 'POST',
data: { },
success: function(data) {
//your code
}
});");
$url = \Yii::$app->urlManager->createUrl(['/your-action-here']);
Write modal code on the view file you are redirecting.
'buttons' => [
'view' => function ($url, $model) {
return Html::a(
'<span class="glyphicon glyphicon-eye-open")></span>',
$url,
[
'class' => 'openModal',
'data-pjax' => 0
]
);
},
'update' => function ($url, $model) {
return Html::a(
'<span class="glyphicon glyphicon-pencil")></span>',
$url,
[
'class' => 'openModal',
'data-pjax' => 0
]
);
},
]
Modal
Modal::begin([
'id' => 'modal-popup',
'size' => 'modal-lg',
'clientOptions' => [
'backdrop' => 'static',
'keyboard' => FALSE
]
]);
echo "<div id='modalContent'></div>";
Modal::end();
JS
$this->registerJs(
"$(document).on('ready pjax:success', function() {
$('.openModal').click(function(e) {
e.preventDefault();
$('#modal-popup').modal('show').find('#modalContent').load($(this).attr('href'));
});
});
");
I've a Yii2-basic application that has view of index.php that contain a kartik GridView. There is an action column that contain view button that will redirect the page to view of view.php if clicked.
If the view button clicked, page will redirect to view.php and show data based on id,
For example from image above, that table contain two button in view column. If the first(top) button clicked, it will show data base on id from id column (left side of table), so it will show data that has id = 1.
And I've successfully create this action.
But I need to show data in modal box. So I use yii\bootstrap\Modal. And I've succesfully show the data in modal box. For the first clicked, it will popup modal box that contain data based on id, but for the next click button it will also show the data based on id that got from the first clicked button.
For example from picture above:
For the first time I click the button from the second row (id = 2) and then popup a modal box that contain data that has id=2, and then I click the button from the first row(id = 1) and it will also popup modalbox that contain data that has id = 2.
Here's my code from index.php:
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\bootstrap\Modal;
<div class="students-index">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' => ['class' => 'table table-hover'],
'columns' => [
[
'label' => 'id',
'value' => function($data) {
return $data->id;
}
],
[
'label' => 'Name',
'value' => function($data) {
return $data->name;
}
],
[
'label' => 'Birthdate',
'value' => function($data) {
return $data->Birthdate;
}
],
[
'label' => 'Sex',
'value' => function($data) {
return $data->Sex;
}
],
[
'class' => 'yii\grid\ActionColumn',
'header' => 'View',
'template' => '{view}',
'buttons' => [
'view' => function ($url, $model) {
$icon = '<span class="glyphicon glyphicon-eye-open"></span>';
return Html::a($icon, $url, [
'title' => Yii::t('app', 'View'),
'data-toggle' => "modal",
'data-target' => "#myModal",
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
$url = Url::toRoute(['/school/students/view', 'id' => $model->faktur_out_id], ['data-method' => 'post',]);
return $url;
}
}
]
],
]);
?>
</div>
<?php
Modal::begin([
'id' => 'myModal',
]);
Pjax::begin([
'id'=>'pjax-modal','timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,
]);
Pjax::end();
Modal::end();
?>
<?php
$this->registerJs("
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var href = button.attr('href')
$.pjax.reload('#pjax-modal', {
'url' => href,
});
"); ?>
How do I can show the data in modal box based on id?
But actually I didn't understand $this->registerJs("......") yet.
Maybe anyone can explain about it in simple language.
Any help will be appreciated, thanks.
$this->registerJs(" ");
is simply a function in the Yii framework that allows you to write the javascript in between the " ".
Try this:
<?php
Modal::begin([
'id' => 'myModal',
]);
Pjax::begin([
'id'=>'myModal','timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,
]);
Pjax::end();
Modal::end();
?>
<?php
$this->registerJs("
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var href = button.attr('href')
$.pjax.reload('#myModal', {
'url' => href,
});
"); ?>
I have a model with a custom validation method. For testing it always returns an error message.
public function rules()
{
return [
...
['staff_ids', 'each', 'rule' => ['string']],
[['staff_ids'], 'validateStaffIds'],
...
];
}
public function validateStaffIds($attribute, $params, $validator) {
$this->addError($attribute, 'There is an error in the staff ids');
}
In the view.php is the modal element
<p>
<?= Html::button('Add Ensemble Staff',
['value' => Url::to(['ensemble/add', 'id' => $model->id]),
'title' => 'Adding New Ensemble Staff',
'class' => 'showModalButton btn btn-primary']);
?>
</p>
<?php
Modal::begin([
'closeButton' => [
'label' => 'x',
],
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
The js code which fires everything up...
$(function(){
$(document).on('click', '.showModalButton', function(){
if ($('#modal').data('bs.modal').isShown) {
$('#modal').find('#modalContent')
.load($(this).attr('value'));
} else {
//if modal isn't open; open it and load content
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
}
//dynamiclly set the header for the modal
...
});
});
And the ensemble controller which handles the add action
public function actionAdd($id)
{
$model = $this->findModel($id);
// in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $id]);
} else {
return $this->renderAjax('add', [
'model' => $model,
]);
}
}
And the form which is injected by the js into the model (Url::to(['ensemble/add', 'id' => $model->id]), )
<?php $form = ActiveForm::begin(['id' => 'add-theater-stuff-form']); ?>
<?= $form->field($model, 'staff_ids')->widget(Select2::className(), [
'model' => $model,
'data' => ArrayHelper::map(app\models\TheaterStaff::find()->where(['theater_id' => $model->theater_id])->all(), 'staff_id', 'staff.fullname'),
'options' => [
'multiple' => true,
'prompt' => 'Ensemble Staff',
],
'pluginOptions' => [
'tags' => true
]
]); ?>
<div class="form-group">
<?= Html::submitButton('Add', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Clicking on the Add Ensemble Staff Button works fine and brings up the modal window. The form itself works fine so far; also the default validation works. Even the custom validation is called, but return $this->renderAjax(...) isn't load in the modal window anymore; it is separately.
A picture showing the modal loaded, the result after submit and a modal with default validation.
I found a similar problem here. But adding an id to the form, doesn't solve the problem. So how to get the default validation showing up properly in the modal window? Does anyone have a clue?
Solution
Thanks for the response. For me the solution was:
Enable ajax in the form
<?php $form = ActiveForm::begin(['id' => 'add-ensemble-stuff-form', 'enableAjaxValidation' => true]); ?>
And to add the following logic in the controller
public function actionAdd($id)
{
$model = $this->findModel($id);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
} else {
// in the post ( 'ensembleStaff_ids' => [0 => '2']); where the id actually is staff_id
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $id]);
} else {
return $this->renderAjax('add', [
'model' => $model,
]);
}
}
}
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}else{/* your code */}
add this in controller use yii\web\Response