Unable to locate message source for category 'mtrelt' - php

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

Related

Getting unknown property in Yii

under the course content there, I want to make the Active column to show either "Yes" or **"No"**At first it was showing "1" or "0", but that's not what I want to show. These are my attempted codes, and I'm getting this error. Appreciate it if anyone can please guide me.
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\models\Coursecontent::isActive
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Course */
$this->title = $model->course_name;
$this->params['breadcrumbs'][] = ['label' => 'Courses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="course-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('<< Back', ['index'], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Update', ['update', 'id' => $model->course_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->course_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'course_name',
'description',
['attribute' => 'active', 'value' => $model->isActive,'contentOptions' => ['style' => $model->active == 1 ? 'color:green' :'color:red']],
'lastupdate',
],
]) ?>
<h2>Course Content</h2>
<?= Html::a('Create Coursecontent', ['coursecontent/create'], ['class' => 'btn btn-success']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'chapter_name',
'description',
'video_link',
['attribute' => 'active',
'value' => function ($model, $key, $index, $column) {return $model->isActive;},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active == 1 ? ['style' => 'color:green'] : ['style' => 'color:red'];
}],
['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'view' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>',['coursecontent/view', 'id' => $model->coursecontent_id]);
},
'update' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',['coursecontent/update', 'id' => $model->coursecontent_id]);
},
'delete' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>',['coursecontent/delete', 'id' => $model->coursecontent_id],
['data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]);
},
]],
],
]); ?>
</div>
Have to make 2 changes to your code.
Change all $model->isActive to $model->active.
Return "Yes" or "No" depending to $model->active value.
Update DetailView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => ['style' => $model->active ? 'color:green' :'color:red']
],
Update GridView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active ? ['style' => 'color:green'] : ['style' => 'color:red'];
}
],

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')],

Pagination with array in yii2

I want to use pagination in my view, but I can't figure out how to do it in conjunction with the find() method.
Getting the numbers of pages works correctly, but it always displays all values from the database. I want to see 15 comments per page.
Here is my ViewAction controller:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'pagination'=> $pagination
]);
}
And this is how I get the comments:
public static function findComment($id)
{
if (($model = UrUser::findOne($id)) !== null) {
$Id=$model->Id;
$comment = UrComment::find()->where(['Rel_User' => $Id])->all();
return $comment;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
I tried to use this:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
$comment= UrComment::findComment($id);
$comment->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' =>$comment,
'pagination'=> $pagination
]);
}
But I get this error:
Call to a member function offset() on array
Then I display it in the view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php foreach ($comment as $comm): ?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comm->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comm->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comm->Text ?></p>
<hr>
<?php endforeach; ?>
<?php
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]);
?>
</div>
</div>
</div>
How can I limit the UrComment::findComment($id) using the pagination?
EDIT:
I think I understand you, and I think I've done everything you told me in your answer, but now I have another problem. I need to display under view comments only that which is id view only this one person not all comments.
Here is what I have now:
ActionView:
public function actionView($id) {
$searchModel = new CommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
CommentSearch:
<?php
namespace backend\modules\users\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UrComment;
class CommentSearch extends UrComment
{
public function rules() {
return [
[['Id'], 'integer'],
[['Text'], 'safe'],
];
}
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params) {
$query = UrComment::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'Id' => $this->Id,
'Text' => $this->Text,
]);
$query->andFilterWhere(['like', 'Text', $this->Text]);
return $dataProvider;
}
}
View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'comments',
'viewParams' => ['comment' => $comment, 'model'=>$model],
]);
?>
</div>
</div>
</div>
And my item comments:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comment->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comment->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comment->Text ?></p>
<hr>
Using that code, now I have error that in this item in button edit:
$comment->Id], ['class' => 'btn btn-primary']) ?>
Trying to get property of non-object
And I can't use foreach there because I have duplicate comments. Should change something in comment Search or in my function findComment(id) inquiry?
There is my actual item 'comments' where I want to display text of comments and buttons to edit and delete comment. But this does not work for me. I have:
Use of undefined constant Id - assumed 'Id'
and
Use of undefined constant Text - assumed 'Text';
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= Text ?></p>
<hr>
If you use model and foreach in not easy, use pagination because pagination if base on dataProvider and not directly for model ..
Essentially finding the model like you did mean work direclty on the data while pagination don't work directly on the data but rather use the a sql query for retrive information from db a let these available to widgets .. this is what the dataProvider perform .. .. then I suggest you of use a widget like ListView and change your query based on a find with a dataProvider based on a modelSearch ..
public function actionView($id) {
$searchModel = new UrCommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
and for view.php
<?php
echo ' <h1>User : ' . $model->userName . '</h1>';
echo '<h2>Comments</h2'>,
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_comment',
]);
where _comment is a partial view of you comment layout .,.
then in _comment.php you can simply
<?=$model->id;?>
<?=$model->text;?>

how to get user selected from multiselect checkbox input in yii2?

Recently I installed the multiSelect check box extension.
my _form.php looks like this:
<? = $ Form-> field ($ model_detail, 'product_id') ->
widget (MultiSelect :: className (),
['id' => "multiXX",
"options" => ['multiple' => "multiple"],
'data' => $ rows,
'attribute' => 'product_id',
'model' => $ models ,
"clientOptions" =>
[
"includeSelectAllOption" => true, 'numberDisplayed' => 2,
],
]);
How can I extract the data chosen by the user in actionCreate of anther model?
how can I get the options that the user selected?
(I tried the $_post[] and it didn't worked.)
this is the whole form:
div class="customer-order2-form">
<?php $form = ActiveForm::begin(['action' => ['create']]); ?>
<?= $form->field($model, 'customer_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'customer_phone')->widget(\yii\widgets\MaskedInput::className(),
[
'mask' => '999-9999999',
'clientOptions' => ['alias' => '972']
]) ?>
<?php /* $form->field($model, 'customer_phone')->textInput(['maxlength' => 255]) **/?>
<?= $form->field($model, 'order_date')->widget(
DatePicker::className(), [
'inline' => false,
// 'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-m-d'
]
]);?>
<?php $model_detail = new OrderDetails2(); /* -------- כאן הוספתי נתונים ממודל
$rows=ArrayHelper::map(ProductFamily::find()->all(), 'id', 'name'); //--- אין צורך בשאילתא, עכשיו גם מציג את מה שנבחר למעלה
?>
<?= $form->field($model_detail, 'product_id')->widget(
MultiSelect::className(), [
'id'=>"multiXX",
"options" => ['multiple'=>"multiple"], // for the actual multiselect
'name' =>'multicheck',
'data' =>$rows,
'attribute' => 'product_id', // if preselected
'model' => $models,
"clientOptions" =>
[
"includeSelectAllOption" => true,
'numberDisplayed' => 2,
],
]);
?>
<?php
echo $form->field($model, 'description')->textarea(['rows' => 6]);
echo /*$form->field($model, 'totalprice')->textInput();*/
$form->field($model, 'totalprice')->widget(MaskMoney::classname(), [
'pluginOptions' => [
'prefix' => '₪ ',
'allowNegative' => false
]
]);
echo $form->field($model, 'status_id')->dropDownList(ArrayHelper::map(Status::find()->select('*')->all(), 'id', 'name'));
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'יצירה' : 'עדכון', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
what i tried is saving to different table in DB with a default Array,
and it worked.
it looks like this:
public function actionCreate()
{
$model = new CustomerOrder2();
$model_details= new OrderDetails2();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
if (isset($_POST['product_id'])){
$model_details->attributes = $_POST['product_id'];
$model_details->attributes=array();
echo
$model_details->attributes;
}
echo $_POST['description'];
$values = Array('1'=>'1','2'=>'2');
$model_details->attributes = $_POST['product_id'];
$array=$model_details->attributes;
//$data=OrderDetails2::->request->post();
//$values= Array(Yii::$app->request->post()['multiXX']);
//$values=Array($model_details->attributes);
foreach($values as $value)
{
$command = Yii::$app->db->createCommand();
$command->insert('order_details',array('Order_id'=>$model->id,
'product_id'=> $value,
'quantityOrdered'=> '1',
));
$command->execute();
}
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}

Not found error in Yii2

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>

Categories