I need this button in grid open a modal , but is not working
this is the column:
['class' => 'yii\grid\ActionColumn',
'template' => '{getRespostaPossivel}',
'buttons' => [
'getRespostaPossivel' => function ($url, $model) {
if($model->classeResposta->indr_resposta_possivel){
return Html::buttonInput('Respostas Possíveis',['class'=>'btn btn-primary btn-xs','id' => 'modal-open','onclick' =>
"$('#modal').modal('show');
$.ajax({
url : 'getFormRespostaPossivel',
data : {'id' : $model->id},
success : function(data) {
$('.modal-body').html(data);
}
});
"]);
}
},
],
],
and action:
public function actionGetFormRespostaPossivel($id)
{
$searchModel = new RespostaPossivelUsuarioSearch();
$searchModel->tblcaus_id = $id;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('_form', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
],true,true);
}
someone could help me with this problem ?
Related
Hello I am trying to post data via ajax but i face this error and i am sure that i called CSRF_TOKEN in header section
Header Section :
meta name="csrf-token" content="{{ csrf_token() }}"
Route Section :
Route::post('cart/data/store/{id}', [CartController::class, 'AddToCart']);
Ajax Code :
function addToCart() {
var product_name = $('#pname').text();
var id = $('#product_id').val();
var color = $('#color option:selected').text();
var size = $('#size option:selected').text();
var quantity = $('#qty').val();
$.ajax({
type:"POST",
dataType:"JSON",
data:{
color:color,
size:size,
quantity:quantity,
product_name:product_name,
},
url: "cart/data/store/"+id,
success:function(data) {
$('#closeModal').click();
console.log(data)
}
})
}
Controller :
class CartController extends Controller
{
public function AddToCart(Request $request, $id) {
$product = Product::findOrFail($id);
if ($product->discount_price == NULL) {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->selling_price,
'weight' => 1,
'options' => [
'image' => $product->product_thumbnail,
'size' => $request->size,
'color' => $request->color,
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
} else {
Cart::add([
'id' => $id,
'name' => $request->product_name,
'qty' => $request->quantity,
'price' => $product->discount_price,
'weight' => 1,
'options' => [
'size' => $request->size,
'color' => $request->color,
'image' => $product->product_thumbnail
],
]);
return response()->json(['success' => 'Item Added To Your Cart']);
}
}
}
Token Section :
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
}
add #csrf in beginning of your form.
<form id="my_form" >
#csrf
<input type="text" name="name"id="name" >
<button type="submit">submit</button>
</form>
I was wondering whether I can call the action automatically through ajax one by one for each row of the GridView after the page is load.
All I can do now is trigger the call manually through button click, already returned the value correctly.
Here is my GridView:
<?php Pjax::begin(['id' => 'payment-list-view-container', 'timeout' => 5000]); ?>
<?= GridView::widget([
'id' => 'payment-table',
'dataProvider' => $dataProvider,
'resizableColumns' => false,
'tableOptions' => ['class' => 'table table-striped'],
'pjax'=>true,
'pjaxSettings' => [
'options' => [
'id' => 'payment-table',
'enablePushState' => false,
],
],
'columns' => [
[
'class' => 'kartik\grid\SerialColumn',
'header' => 'No.',
],
[
'header' => 'Title',
'attribute' => 'name',
],
[
'attribute' => 'date_start',
'header' => 'Payment Date',
'value' => function($model){
return Yii::$app->formatter->asDatetime($model->payment_date, "php:d F Y");
}
],
[
'header' => 'Action',
'format' => 'raw',
'value' => function($model) use ($export_type){
return Html::a('Open', '',
[
'data-url'=>'/model/payment/check-status/id/'. $model->id . '?exportType=' . $export_type ,
'class'=>'check-payment-status'
]);
}
],
],
]); ?>
<?php Pjax::end(); ?>
Here is my js:
<?php
$js = <<<JS
$(document).ready(function(){
function checkStatus() {
$(".check-payment-status").off().on("click", function(e){
e.preventDefault();
var url = $(this).attr("data-url");
$.pjax.defaults.timeout = false;
$.ajax({
url : url,
type : "post",
dataType: 'json',
success: function (response) {
// do something
}, error : function () {
// do nothing
}
});
});
}
checkStatus();
});
JS;
$this->registerJs($js);
I guess I need to use something like this, but still don't know how to implement it
$.each($('.check-payment-status'), function (i, el) {
//do something
});
So can I really do that? Calling the action automatically after the page load for each row?
All you need to do is to trigger the click event on the buttons.
$(document).ready(function() {
//bind the click handler
$('.btn').on('click', function(e) {
e.preventDefault();
console.log("Clicked " + $(this).text());
});
//click each button
$('.btn').each(function() {
$(this).trigger('click');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link 1<br>
Link 2<br>
Link 3<br>
I have a view like this:
// snippet of view
<td><input class="form-field" type="text" id="entity" name="name" data="{{$entity->id}}" value="{{$entity->name}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>
<td><input class="form-field" type="text" id="entity" name="type" value="{{$entity->type}}" onkeyup="validation(this.value);" onblur="updateEntity(this.value,this.name,this.id,{{$entity->id}})"></td>
Which has an ajax:
function updateEntity(value, name, data, id) {
$.ajax({
url: '/entityadmin/' + value + '/' + name + '/' + data + '/' + id,
method: 'POST',
dataType: 'json',
success: function(save) {
$('.messages').append('<div class="alert alert-success">Type Updated!<div>');
setTimeout(function() {
$(".alert").fadeTo(2000, 500).slideUp(500, function(){
$(".alert").slideUp(500);
});
}, 4000);
},
error: function(data) {
console.log(data);
$('.messages').append('<div class="alert alert-danger">Error, please try again!<div>');
setTimeout(function() {
$(".alert").fadeTo(2000, 500).slideUp(500, function(){
$(".alert").slideUp(500);
});
}, 4000);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Controller:
public function entityUpdate($value, $name, $data, $id, EntityRequestUpdate $request) {
$request->$name = $value; //like this?
if($data == "entity") {
$save = Entity::find($id);
}else{
$save = User::find($id);
}
$save->$name = $value;
$save->save();
return response()->json(['results' => $save]);
}
and request:
public function rules()
{
return [
'startdate' => 'required|date',
'endate' => 'nullable|date',
'startime' => 'required|time',
'endtime' => 'required|time',
'title' => 'required',
'type' => 'required',
'description' => 'required',
'frequency' => 'required',
'interval' => 'nullable|numeric',
'monthday' => 'nullable|numeric|min:1|max:3',
'weekday' => 'nullable|alpha|max:3',
'month' => 'nullable|numeric',
'until' => 'nullable|date',
'tags' => 'nullable',
'img' => 'nullable|file|image',
];
}
The thing is it only has to validate one field because one field is being changed each time, how can I use this validation to validate the incoming variable and return errors to ajax with the message on the error if there is any?
You can manually create a validator to validate this one field like so:
$validator = Validator::make(
[ 'name' => $value ],
collect($this->rules())->only([$name])->all()
);
This validator will take the name validator from the defined rules and check that against the first array of values.
How can I do: I have 2 multi-select fields Select2, the first field for Branches, second for Workers.
When I choose branches, in second field I need to show Workers, who work in this branches.
View file
<label><?= $model->getAttributeLabel('branch') ?></label>
<?php echo Select2::widget([
'name' => 'branch',
'id' => 'branches',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => $branchList,
'options' => [
'placeholder' => Yii::t('app', 'Choose branch'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);?>
<label><?= $model->getAttributeLabel('Workers') ?></label>
<?php echo Select2::widget([
'name' => 'worker',
'id' => 'workers',
'theme' =>Select2::THEME_BOOTSTRAP,
'value' => '',
'data' => [],
'options' => [
'placeholder' => Yii::t('app', 'Choose workers'),
'multiple' => true,
],
'pluginOptions' => [
'tags' => true,
'allowClear' => true,
],]);
?>
JS
$("#branches").change(function(){
change();
});
function change() {
var selectValue = $("#branches").val();
$("#workers").empty();
$.post( "'.Yii::$app->urlManager->createUrl('constructor/lists?id=').'"+selectValue,
function(data){
$("#workers").html(data);
}
);
};
ConstructorController
public function actionLists($id)
{
if ($id != null) {
$ids = explode(",", $id);
foreach ($ids as $id_branch) {
$workers = Report::getWorkers($id_branch);
if (count($workers) > 0) {
foreach ($workers as $worker) {
echo "<option value='" . $worker . "'>" . $worker . "</option>";
}
} else {
echo "'<option>-</option>'";
}
}
}
}
i want add a new action in my controller in yii2 project :
i have error for add any new action !
new action have this error : Not Found (#404)
<?php
namespace soft\controllers;
use Yii;
use soft\models\Reserve;
use soft\models\ReserveSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
/**
* ReserveController implements the CRUD actions for Reserve model.
*/
class ReserveController extends Controller {
/**
* #inheritdoc
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
'bulk-delete' => ['post'],
],
],
];
}
/**
* Lists all Reserve models.
* #return mixed
*/
public function actionIndex() {
$searchModel = new ReserveSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionJson() {
die;
}
/**
* Displays a single Reserve model.
* #param string $id
* #return mixed
*/
public function actionView($id) {
$request = Yii::$app->request;
if ($request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'title' => "Reserve #" . $id,
'content' => $this->renderAjax('view', [
'model' => $this->findModel($id),
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
}
/**
* Creates a new Reserve model.
* For ajax request will return json object
* and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate() {
$request = Yii::$app->request;
$model = new Reserve();
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Create new Reserve",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($model->load($request->post()) && $model->save()) {
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Reserve",
'content' => '<span class="text-success">Create Reserve success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return [
'title' => "Create new Reserve",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
}
/**
* Updates an existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
* #param string $id
* #return mixed
*/
public function actionUpdate($id) {
$request = Yii::$app->request;
$model = $this->findModel($id);
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Update Reserve #" . $id,
'content' => $this->renderAjax('update', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($model->load($request->post()) && $model->save()) {
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Reserve #" . $id,
'content' => $this->renderAjax('view', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return [
'title' => "Update Reserve #" . $id,
'content' => $this->renderAjax('update', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
}
/**
* Delete an existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
* #param string $id
* #return mixed
*/
public function actionDelete($id) {
$request = Yii::$app->request;
$this->findModel($id)->delete();
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
} else {
/*
* Process for non-ajax request
*/
return $this->redirect(['index']);
}
}
/**
* Delete multiple existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
* #param string $id
* #return mixed
*/
public function actionBulkDelete() {
$request = Yii::$app->request;
$pks = explode(',', $request->post('pks')); // Array or selected records primary keys
foreach ($pks as $pk) {
$model = $this->findModel($pk);
$model->delete();
}
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
} else {
/*
* Process for non-ajax request
*/
return $this->redirect(['index']);
}
}
/**
* Finds the Reserve model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param string $id
* #return Reserve the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = Reserve::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
why action json is
not found but action create is Available ؟!
this is working :admin2.localhost/en/reserve/create
but this is not working : admin2.localhost/en/reserve/json
this is my main.php :
<?php
$params = array_merge(
require (__DIR__ . '/../../common/config/params.php'),
require (__DIR__ . '/params.php')
);
$config = [
'id' => 'app-soft',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'soft\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'main\models\custom\SoftUser',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'aaaaaaaaaaaaaaa',
],
'runtime'=>[
'class'=>'soft\config\Runtime',
],
'urlManager' => [
'rules' => [
'package' => 'site/package',
],
],
],
'params' => $params,
];
return $config;
Thank you for your guidance.
my params.php have problem and fixed :
'urlRules' => [
'' => 'site/index',
'login/' => 'site/login',
'signup/' => 'site/signup',
'<controller:[\w-]+>/<action:\w+>' => '<controller>/<action>',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/create' => '<controller>/create',
'<controller:[\w-]+>/update/<id:\d+>' => '<controller>/update',
'<controller:[\w-]+>/delete/<id:\d+>' => '<controller>/delete',
'<controller:[\w-]+>/bulk-delete' => '<controller>/bulk-delete',
]