Not found error in Yii2 - php

I am new to yii2 framework. I have created a controller,model and view. But i am getting not found error(404).
I have create the controller TestController.php, a view create.php and a model Test.php. I have try to run my project in particular controller that time im getting not found error message.
This is my controller page
The controller extends by Controller class. I've using alert boxes in controller page but i hasn't get in any alert.
class TestController extends Controller
{
namespace livefactory\modules\test\controllers;
public function actionCreate()
{
if(!Yii::$app->user->can('Test.Create')){
throw new NotFoundHttpException('You dont have permissions to view this page.');
}
$img = new ImageUpload();
$emailObj = new SendEmail;
$model = new Test;
return $this->render('create', [
'model' => $model,
]);
}
}
My model page
The model page defines all the variables used in the particular controller.
The table name is also defined.
namespace livefactory\models;
class Test extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'tbl_test';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Name', 'Relationship', 'Age', 'Mail', 'Status'], 'required'],
[['Age'], 'integer'],
[['Name', 'Relationship', 'Mail', 'Status'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'Name' => Yii::t('app', 'Person Name'),
'Relationship' => Yii::t('app', 'Relationship'),
'Age' => Yii::t('app', 'Age'),
'Mail' => Yii::t('app', 'Mail'),
'Status' => Yii::t('app', 'Status'),
}
}
My view page
<?php
use yii\helpers\Html;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use livefactory\models\Country;
use livefactory\models\State;
use livefactory\models\City;
use kartik\widgets\DepDrop;
use kartik\datecontrol\DateControl;
use livefactory\models\CustomerType;
/**
* #var yii\web\View $this
* #var common\models\Customer $model
*/
$this->title = Yii::t('app', 'Add Person', [
'modelClass' => 'Test',
]);
// $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Customers'), 'url' => ['index']];
// $this->params['breadcrumbs'][] = $this->title;
?>
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5><?= Html::encode($this->title) ?> <small class="m-l-sm"><?php echo Yii::t ( 'app', 'Enter Person Details' ); ?></small></h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="customer-form">
<?php
$form = ActiveForm::begin ( [
'type' => ActiveForm::TYPE_VERTICAL
] );?>
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"><?php echo Yii::t ( 'app', 'Person Details' ); ?></h3>
</div>
<div class="panel-body">
<?php
echo Form::widget ( [
'model' => $model,
'form' => $form,
'columns' => 4,
'attributes' => [
'Person Name' => [
'type' => Form::INPUT_TEXT,
'options' => [
'placeholder' => Yii::t ( 'app', 'Enter Person Name' ).'...',
'maxlength' => 255
],
'columnOptions' => [
'colspan' => 3
]
]
,
'Relationship' => [
'type' => Form::INPUT_TEXT,
'options' => [
'placeholder' => Yii::t ( 'app', 'Enter Relationship' ).'...',
'maxlength' => 255
],
'columnOptions' => [
'colspan' => 3
]
]
]
]
);
echo Form::widget ( [
'model' => $model,
'form' => $form,
'columns' => 3,
'attributes' => [
'Age' => [
'type' => Form::INPUT_TEXT,
'options' => [
'placeholder' => Yii::t ( 'app', 'Enter Age' ).'...',
'maxlength' => 255
]
],
'Mail' => [
'type' => Form::INPUT_TEXT,
'options' => [
'placeholder' => Yii::t ( 'app', 'Enter Mail' ).'...',
'maxlength' => 255
]
],
'Status' => [
'type' => Form::INPUT_TEXT,
'options' => [
'placeholder' => Yii::t ( 'app', 'Enter Status' ).'...',
'maxlength' => 255
]
]
]
] );
?>
</div></div>
<?php
// echo Html::submitButton ( $model->isNewRecord ? Yii::t ( 'app', 'Create' ) : Yii::t ( 'app', 'Update' ), [
// 'class' => $model->isNewRecord ? 'btn btn-success customer_submit' : 'btn btn-primary customer_submit'
// ] );
ActiveForm::end ();
?>
</div>
</div>
</div>

Related

Trying to get property 'id' of non-object yii2

I'm trying to render a Nav bar (from _tabs.php) onto index.php (view) the controller that is being used is ImportController.php. the _tabs.php file uses the client_id which is basically the function to get the client ID so it can appropriately create the URL with an ID in it. The issue that I'm getting is Trying to get property 'id' of non-object
index.php (view)
<?php
use yii\bootstrap\Html;
use common\components\ActiveForm;
use common\models\User;
use common\models\Client;
$Client= null;
$this->title = 'Import Offline Data Capture data';
?>
<!-- capture partial Nav -->
<br>
<?php if(in_array(Yii::$app->user->identity->role, User::MHM_ROLES)): ?>
<?= $this->render('/client/_tabs', ['Client' => $Client]); ?>
<?php endif; ?>
<?php if(in_array(Yii::$app->user->identity->role, User::CLIENT_ROLES)): ?>
<?= $this->render('//client/partialNavs/appendNav', ['Client' => $Client]); ?>
<?php endif; ?>
<div class="page-header">
<h2>Import data</h2>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-body" id="survey-import-container">
<h4 class="text-info">Please select a file to import</h4>
<?php if(count($ImportForm->getErrors('dataErrors'))): ?>
<div class="alert alert-warning">
<p><strong>Sorry, we were unable to process your import. Please revise the following errors and try again:</strong><p><br />
<ul>
<?php foreach($ImportForm->getErrors('dataErrors') as $e): ?>
<li><?= $e; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<p>The file must follow the exported template, and must be a XLSX document with a maximum of 10,000 rows.</p>
<?php $form = ActiveForm::begin([
'id' => 'import-form',
'options' => [
'enctype' => 'multipart/form-data',
'class' => 'clearfix',
]
]) ?>
<?= $form->field($ImportForm, 'importFile')->fileInput() ?><hr />
<?= Html::submitButton('<span class="glyphicon glyphicon-import"></span> Import & Process Data', ['class' => 'btn btn-primary col-md-6', 'id' => 'import-data-btn']); ?>
<?= Html::a('<span class="glyphicon glyphicon-repeat"></span> Reset', ['import/index'], ['class' => 'btn btn-link col-md-6']); ?>
<?php ActiveForm::end() ?>
<div class="alert alert-danger" style="margin-top: 20px;">Please note: This application does not store any of your imported data. Keep your original spreadsheet to avoid losing data.</div>
</div>
</div>
</div>
</div>
ImportController.PHP
<?php
namespace admin\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use admin\components\Controller;
use admin\models\ImportForm;
use common\models\User;
use common\models\Client;
class ImportController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index'],
// All actions are access controlled.
'roles' => [
User::ROLE_MHM_ADMIN,
User::ROLE_MHM_USER,
User::ROLE_CLIENT_ADMIN,
User::ROLE_CLIENT_USER,
]
],
],
],
];
}
public function actionIndex($client_id = null)
{
// Get client
$Client = $this->getClient($client_id);
// Ensure client exists for logged in user
if(is_null($Client)) {
throw new BadRequestHttpException('This page does not exist.');
}
$ImportForm = new ImportForm;
// Form posted, validate
if(Yii::$app->request->isPost) {
$ImportForm->importFile = UploadedFile::getInstance($ImportForm, 'importFile');
// Process upload
$ImportForm->upload();
}
return $this->render('index', array(
'ImportForm' => $ImportForm,
));
}
public function actionRenderSuccess()
{
return $this->renderPartial('_success');
}
private function getClient($id, $restriction = null)
{
if(Yii::$app->user->identity->client_id)
{
$id = Yii::$app->user->identity->client_id;
}
$ClientQuery = Client::find()
->andWhere(['id' => $id]);
if ($restriction == 'patronbase') {
$ClientQuery->andWhere(['license_type' => Client::LICENSE_PATRONBASE]);
} else if ($restriction == 'live') {
$ClientQuery->andWhere(Client::LIVE_OR_UPGRADING_CONDITION);
}
$Client = $ClientQuery->one();
if(is_null($Client))
{
throw new NotFoundHttpException('');
}
return $Client;
}
}
_tabs.php
<?php
use yii\bootstrap\Html;
use common\models\Client;
use common\models\User;
use common\models\SurveyInstance;
use common\models\Consent;
use yii\bootstrap\Tabs;
use yii\bootstrap\Nav;
if (Yii::$app->user->isGuest) return;
$getRoute = function($route, $clientParamName, $otherParams = []) use ($Client)
{
$routeParams = [$route];
if (!isset(Yii::$app->user->identity->client_id)) {
$routeParams[$clientParamName] = $Client->id;
}
return array_merge($routeParams, $otherParams);
};
$route = Yii::$app->controller->module->requestedRoute;
$mhmOrClientAdmin = in_array(Yii::$app->user->identity->role, [User::ROLE_MHM_ADMIN, User::ROLE_MHM_USER, User::ROLE_CLIENT_ADMIN]);
$mhmUser = in_array(Yii::$app->user->identity->role, User::MHM_ROLES);
$urlsForConsentSurveyTypes = Consent::getUrlForSurveyTypes();
$items = [
[
'label' => 'Checkout / Enrich',
'url' => $getRoute('dashboard/mhm-rels-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/mhm-rels-dashboard',
'survey-instance/api-logs',
'client/activity',
'client/update',
'client/api-settings'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
'encode' => false,
'visible' => $Client->isFullOrUpgrading,
],
[
'label' => 'Checkout / Enrich',
'url' => $getRoute('dashboard/patronbase-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/mhm-rels-dashboard',
'dashboard/patronbase-dashboard',
'survey-instance/api-logs',
'client/activity',
'client/update',
'client/api-settings',
'client/patronbase-settings'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
'encode' => false,
'visible' => $Client->license_type === Client::LICENSE_PATRONBASE,
],
[
'label' => 'Capture',
'url' => $getRoute('dashboard/capture-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/capture-dashboard',
'client/survey-settings',
'consent/create',
'consent/update',
'question/index',
'client/legal',
'question/create',
'question/update'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='capture-consent'),
'encode' => false,
],
[
'label' => 'Append',
'url' => $getRoute('dashboard/append-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/append-dashboard',
'client/append-settings',
'import/index'
]),
'encode' => false,
],
//Info
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Info',
'options' => ['class' => 'pull-right'],
'active' => in_array($route, [
'client/stats',
'client/survey-urls',
]),
'encode' => false,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Stats',
'url' => $getRoute('client/stats', 'client_id'),
'active' => in_array($route, ['client/stats',]),
'encode' => false,
'visible' => $mhmOrClientAdmin,
],
[
'label' => '<span class="glyphicon glyphicon-file"></span> Guides',
'url' => '/guides/' . $Client->hash,
'encode' => false,
'linkOptions' => [ 'target' => '_blank'],
'visible' => $Client->isFullOrUpgrading,
],
[
'label' => '<span class="glyphicon glyphicon-link"></span> Survey URLs',
'url' => $mhmUser ? ['client/survey-urls', 'client_id' => $Client->id] : ['client/survey-urls'],
'encode' => false,
],
],
],
//Settings
[
'label' => '<span class="glyphicon glyphicon-cog"></span> Account settings',
'options' => ['class' => 'pull-right'],
'active' => in_array($route, [
'client/anonymisation',
'contact/index',
'contact/update',
'contact/create',
'contact/delete',
'user/index',
'user/create-update',
]),
'encode' => false,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-erase"></span> Anonymisation',
'url' => $getRoute('client/anonymisation', 'id'),
'active' => in_array($route, ['client/anonymisation']),
'encode' => false,
],
[
'label' => '<span class="glyphicon glyphicon-envelope"></span> Email List',
'url' => $getRoute('contact/index', 'client_id'),
'active' => in_array($route, [
'contact/index',
'contact/update',
'contact/create',
'contact/delete',
]),
'encode' => false,
],
[
'label' => '<span class="glyphicon glyphicon-user"></span> Users <span class="badge">'.count($Client->clientUsers).'</span>',
'url' => $getRoute('user/index', 'client_id'),
'active' => in_array($route, [
'user/index',
'user/create-update',
]),
'encode' => false,
'visible' => $mhmOrClientAdmin,
],
],
],
];
echo Nav::widget([
'options' => [
'class' => 'nav nav-pills',
'id'=>'nav-bar',
],
'items' => $items,
]);
?>
<style>
#nav-bar {
background-color: aliceblue
}
</style>
Hope this answer will help:
return $this->render('index', array(
'ImportForm' => $ImportForm,
'Client' => $Client
));
Focus on your Index action on ImportController. I think you forgot to pass that $Client to index.php.
Also, remove $Client= null; in your view file (index.php) above $this->title;

Yii2 - DynamicModel validation

I have a form and I want to change my DynamicModel rule validations depedending on the value chosen in a specific select input. I've read this doc but I don't understand why my code doesn't work. I've tried the following with no results:
MyController
private function createFormModel(){
$model = new DynamicModel([
'indicador',
'mes'
]);
$model->addRule(['indicador'], 'required',['message' => 'This field is required']);
$model->addRule(['mes'], 'string');
$model->addRule(
'mes',
function ($attribute, $params, $validator) use ($model) {
if ($model->indicador == 'semana') {
$model->addError('mes', 'This field is required');
}
}
);
return $model;
}
MyView
<?php $form = ActiveForm::begin(); ?>
<!-- indicador -->
<div class="form-group">
<?= $form->field($model, 'indicador')->widget(Select2::class, [
'options' => ['id'=>'indicador'],
'data' => [
'dia' => 'Actividad por Día',
'semana' => 'Actividad por Semana',
'resumen' => 'Resumen de actividad'
],
'pluginOptions' => [
'placeholder'=>'Seleccionar indicador',
'allowClear' => true
],
]); ?>
</div>
<!-- /.indicador -->
<!-- mes -->
<div id = "semana" class="form-group hidden">
<?= $form->field($model, 'mes')->widget(DepDrop::class, [
'type' => DepDrop::TYPE_SELECT2,
'options' => ['id' => 'mes'],
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['indicador'],
'placeholder'=>'Seleccionar mes',
'url' => Url::to(['/campus/subindicador']),
'loadingText' => 'Cargando ...',
'initialize' => true,
]
]);?>
</div>
<!-- /.mes -->
<?= Html::submitButton('Aplicar filtros', ['class' => 'btn btn-block btn-default']) ?>
<?php ActiveForm::end(); ?>
You need to use when with required validator.
$model = new DynamicModel(['indicador', 'mes']);
$model->addRule(['indicador'], 'required', ['message' => 'This field is required']);
$model->addRule(['mes'], 'string');
$model->addRule(['mes'], 'required', ['when' => function ($dModel) {
return $dModel->indicador == 'semana';
}, 'message' => 'This field is required']);

My filter on index.php is not working

The model is Booking.php. I need to get data from another model called ServiceCategory.php and add a filter to it in Gridview on my index.php. I created filter on view/index.php as below.
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(app\models\Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
This is my index.php
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\models\Servicecategory;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BookingSerach */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bookings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="list-booking">
<h1 class=""><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p class="form-inline text-right">
<label>Client:</label>
<?= Html::dropDownList('client', null, ArrayHelper::map($clients, 'id', 'fullname'), ['prompt' => 'Please Select', 'class' => 'form-control']) ?>
<?= Html::a('+ New Booking', ['booking/create/'], ['class' => 'btn btn-primary client-create']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'value' => 'user.client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
//'numberOfDays',
//'date',
//'followUpEmail:email',
// 'followUpEmailSent:ckeckbox',
//'Status',
['attribute' => 'status', 'value' => 'Status', 'filter' => array_filter(\app\models\Booking::$statuses)],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp(this, "' . $url . '")', 'checked' => false, 'id' => 'followup'];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:15%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
},
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
},
],
],
],
]);
?>
</div>
<?php
$script = <<< JS
$('.client-create').on('click', function () {
select = $(this).prev();
if(select.val()){
location.href = $(this).attr('href')+"/"+select.val();
} else {
$(this).parent().addClass('has-error');
}
return false;
});
JS;
$this->registerJs($script);
$this->registerJs("
function followUp(e, url){
$('#modal').modal('show').find('#modalContent').load(url);
}", yii\web\View::POS_END);
?>
I can get the data to the column on gridview but the filter is not working. Can anyone help me with this?
I solved it myself. For your information I post it here. I changed the attribute as the model contains and added the value as category.name
['attribute' => 'categoryID', 'value' => 'category.name','filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],

Unable to locate message source for category 'mtrelt'

If I try to update records,I get following error without any ideas, what's about or what this error could have been caused by.
Furthermore, it's strange, that this error only will be bred by records having been imported by a dump. There will be no error, if I will update a record having been created using saveasnew option. Unfortunately, I can't delete this record in order to recreate it,'cause it would expel against referential integrity.
Here is error:
Invalid Configuration – yii\base\InvalidConfigException
Unable to locate message source for category 'mtrelt'.
throw new InvalidConfigException("Unable to locate message source for category '$category'.")
2. in ...\vendor\yiisoft\yii2\i18n\I18N.php at line 88 – yii\i18n\I18N::getMessageSource('mtrelt')
3. in ...\vendor\yiisoft\yii2\BaseYii.php at line 509 – yii\i18n\I18N::translate('mtrelt', 'Data can't be deleted because it...', [], 'de-DE')
4. in ...\vendor\mootensai\yii2-relation-trait\RelationTrait.php at line 312 – yii\BaseYii::t('mtrelt', 'Data can't be deleted because it...')
Here is model:
<?php
namespace common\modules\lookup\models\base;
use Yii;
use mootensai\behaviors\UUIDBehavior;
class LPersonArt extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
public function relationNames()
{
return [
'eAppEinstellungArts',
'lKontaktVerwendungszwecks',
'people'
];
}
public function rules()
{
return [
[['person_art'], 'string', 'max' => 50],
[['zieltabelle'], 'string', 'max' => 100],
[['bemerkung'], 'string', 'max' => 255]
];
}
public static function tableName()
{
return 'l_person_art';
}
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'person_art' => Yii::t('app', 'Personengruppen'),
'zieltabelle' => Yii::t('app', 'Zieltabelle'),
'bemerkung' => Yii::t('app', 'Bemerkung'),
];
}
public function getEAppEinstellungArts()
{
return $this->hasMany(\common\modules\erweiterung\models\EAppEinstellungArt::className(), ['id_person_art' => 'id']);
}
public function getLKontaktVerwendungszwecks()
{
return $this->hasMany(\common\modules\lookup\models\LKontaktVerwendungszweck::className(), ['id_person_art' => 'id']);
}
public function getPeople()
{
return $this->hasMany(\common\modules\basis\models\Person::className(), ['id_person_art' => 'id']);
}
public function behaviors()
{
return [
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
public static function find()
{
return new \common\modules\lookup\models\LPersonArtQuery(get_called_class());
}
}
Here is Controller:
public function actionUpdate($id)
{
$model = new LPersonArt();
if (!Yii::$app->request->post('_asnew') == '1'){
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Here is view:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="lperson-art-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'id', ['template' => '{input}'])->textInput(['style' => 'display:none']); ?>
<?=
$form->field($model, 'person_art')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 50,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<?=
$form->field($model, 'bemerkung')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 255,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<div class="form-group">
<?php if (Yii::$app->controller->action->id != 'save-as-new'): ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php endif; ?>
<?php if (Yii::$app->controller->action->id != 'create'): ?>
<?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn btn-info', 'value' => '1', 'name' => '_asnew']) ?>
<?php endif; ?>
<?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer, ['class' => 'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Problem will be solved adding following code into components of
common/config/main-local.php
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages', // if advanced application, set #frontend/messages
'sourceLanguage' => 'de',
],
],
],
I was having a similar problem, but the Yii2 error message was
Unable to locate message source for category ''
I was running Gii from console:
php yii gii/crud --controllerClass="app\controllers\StcDocumentTypeController" --messageCategory="stc_document_type" --enableI18N=1 --enablePjax=1 --interactive=0 --modelClass="app\models\StcDocumentType" --searchModelClass="app\models\StcDocumentTypeSearch" --overwrite=1
The solution was to add the i18n configuration on the console.php config file:
'components' => [
...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en-US',
],
]
],
...
]
If you're running from web check also that config in web.php

how to disable update in gridview for pjax in yii2?

I am new in yii2, Right now i am creating sample crud appliacation. I used pjax for gridview, It is working fine for me, My problem is when i update my row at that time pjax also calling now i want to disable this pjax for update button. How can i resolve this issue ? Here is my code
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PostSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Posts';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Post', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php \yii\widgets\Pjax::begin(
['id' => 'StickerList', 'timeout' => false, 'enablePushState' => false, 'clientOptions' => ['method' => 'GET']]
); ?>
<?= GridView::widget([
'dataProvider' => $model->search(),
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'PostType',
'filter'=>Html::activeDropDownList($model, 'PostType',array(""=>"All","1"=>"Status","2"=>"Images","3"=>"Video"),['class'=>'form-control','prompt' => 'Select Post Type']),
],
'PostTitle',
[
'header' => 'Artist',
'attribute' => 'ArtistName',
],
[
'header' => 'Date Posted',
'attribute' => 'DatePosted',
'filter' => false,
],
[
'header' => '# Likes',
'attribute' => 'TotalLikes',
'filter' => false,
],
[
'header' => '# Comments',
'attribute' => 'TotalComments',
'filter' => false,
],
[
'header' => 'Exclusive',
'attribute' => 'IsExclusive',
'filter'=>Html::activeDropDownList($model, 'IsExclusive',array(""=>"All","0"=>"Normal","1"=>"Exclusive"),['class'=>'form-control','prompt' => 'Select Exclusive']),
],
[
'header' => 'Status',
'attribute' => 'Status',
'filter'=>Html::activeDropDownList($model, 'Status',array(""=>"All","1"=>"Active","2"=>"Inactive"),['class'=>'form-control','prompt' => 'Select Status']),
],
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url);
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>
You should need to add [ 'data-pjax' => false ] or [ 'data-pjax' => '0' ] in anchor tag options of update button.
For example,
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url, ['data-pjax' => '0']);
},
],
]

Categories