Call to a member function saveAs() on a non-object[Yii 2] - php

I am new to yii and php.
I want to upload a file and save its path to database but while doing so I got an error.
My controller class is:
public function actionCreate()
{
$model = new Quiz();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$fileName = $model->name;
$model->file =UploadedFile::getInstance($model,'file');
$model->file->saveAs('uploadQuiz/'.$fileName.'.'.$model->file->extension );
$model->filePath = 'uploadQuiz/'.$fileName.'.'.$model->file->extension ;
$model->save();
return $this->redirect(['view', 'id' => $model->idQuiz]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
My database column name where I save my file path is "filePath".
My view file is:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Quiz */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="quiz-form">
<?php $form = ActiveForm::begin(['option' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'Course_idCourse')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'duration')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'time')->textInput() ?>
<?= $form->field($model, 'file')->fileInput(); ?>
<?= $form->field($model, 'totalMarks')->textInput(['maxlength' => 100]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My rules and attributes are:
public function rules()
{
return [
[['Course_idCourse', 'duration', 'time'], 'required'],
[['Course_idCourse', 'duration', 'totalMarks'], 'integer'],
[['time'], 'safe'],
[['file'],'file'],
[['name', 'filePath'], 'string', 'max' => 200],
[['description'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idQuiz' => 'Id Quiz',
'Course_idCourse' => 'Course Id Course',
'name' => 'Name',
'description' => 'Description',
'duration' => 'Duration',
'time' => 'Time',
'file' => 'Quiz ',
'totalMarks' => 'Total Marks',
];
}
Now I already refer this site for the same question but I find it for update not for create . kINDLY HELP ME.
When I run try to create I got an error
Call to a member function saveAs() on a non-object
I don't figure where am I going wrong.

No file is being uploaded. The option parameter in the ActiveForm initialization should be options
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

Related

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 make different rules in yii2, depends on the radiobutton value?

I'm a begginer so sorry if it's obvious. So, I would like different rules depends on what the user select. I have an update form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'news_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'news_content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'check')->label('Picture update:')
->radioList(
[ 2 => 'Yes', 1 => 'No', 0 => 'Delete']) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And only if the radioList has a value '2' I would like to require the fileInput. I mean if the user select 1 => 'No', or 0 => 'Delete' the fielInput can be empty.
public function rules() {
return [
[['news_content'], 'string'],
[['news_content'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['news_title'], 'required'],
[['news_picture'], 'required'],
[['file'], 'file', 'skipOnEmpty' => $this->checkRadio(), 'extensions' => 'png, jpg',],
[['check'], 'required', 'message' => 'Please ....'],
];
}
public function checkRadio() {
if ($this->check == 2) {
return false;
} else {
return true;
}
}
I tried to write a function in the model but the $check variable always has a 0 value and I don't really understand why. Is there any solution in Yii2 for this?
Here is the documentation which is quite straight forward but something like this should be sufficient
[
'file', 'required',
'when' => function ($model) {
return $model->check == 2;
},
'whenClient' => "function (attribute, value) {
return $('#signupform-check-2').is(':checked');
}",
'message' => 'Please....'
]
As long as you have client validation enabled, you always have to do two checks. backend and front end.
*********** Your Controller Like This ***********************
public function actionCreate(){
$model = new Model();
if(Yii::$app->request->post())
{
if($model->check ==2)
{
$model->scenario ='fileInputRequired';
}
else{
$model->scenario ='fileInputNotRequired';
}
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
********** Your Model Like This *****************
public function rules() {
return [
[['news_content','news_title','news_picture','check'], 'required'],
[['news_content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['file'], 'file', 'on' =>'fileInputRequired', 'extensions' => 'png, jpg',],
];
}
function scenario()
{
return [
'fileInputRequired' => ['news_content', 'news_picture', 'news_title','file','check'];
'fileInputNotRequired' => ['news_content', 'news_picture','news_title','check'];
}

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,
]);
}
}

How to implement kartik yii2 FileInput in form which is using different model

Here is the code located in myyiiapp\backend\views\product_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\FileInput;
/**
* #var yii\web\View $this
* #var backend\models\Product $model
* #var yii\widgets\ActiveForm $form
*/
?>
<div class="product-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'category_id')->textInput() ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'last_updated')->textInput() ?>
<?= $form->field($model, 'documentation')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'layout')->textInput() ?>
<?=
// Usage with ActiveForm and model
$form->field($model, 'someAttributeName')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]);
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I have a table name "product" and I have another table name "product_images" which contain product image path and product id column.
How can I set attribute where it says someAttributeName for image which is in ProductImage model and this form is using Product model. In short how can we use multiple model in here and I need to create product first then image path because to save image path I need product id which is going to be auto generated by mysql.
I have generated everything from Yii2 crud.
Finally after too many trial and error I've found the solution of my own question.
View : _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\FileInput;
/**
* #var yii\web\View $this
* #var backend\models\Product $model
* #var yii\widgets\ActiveForm $form
*/
?>
<div class="product-form">
<!--change here: This form option need to be added in order to work with multi file upload ['options' => ['enctype'=>'multipart/form-data']]-->
<?php $form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'category_id')->dropDownList($model->getCategoryList()) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'last_updated')->textInput() ?>
<?= $form->field($model, 'documentation')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'layout')->textInput() ?>
<?php
// Usage with ActiveForm and model
//change here: need to add image_path attribute from another table and add square bracket after image_path[] for multiple file upload.
echo $form->field($productImages, 'image_path[]')->widget(FileInput::classname(), [
'options' => ['multiple' => true, 'accept' => 'image/*'],
'pluginOptions' => [
'previewFileType' => 'image',
//change here: below line is added just to hide upload button. Its up to you to add this code or not.
'showUpload' => false
],
]);
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Controller
public function actionCreate()
{
$model = new Product;
$productImages = new ProductImages;
if($_POST){
//below line will fetch all image related data and put it into $file as an object. Refer output of var_dump($file) after controller code.
$file = UploadedFile::getInstances($productImages, 'image_path');
var_dump($file);
}
//below code is where you will do your own stuff. This is just a sample code need to do work on saving files
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'productImages' => $productImages,
]);
}
}
var_dump($file) This will show output of uploaded image data.
array (size=3)
0 =>
object(yii\web\UploadedFile)[45]
public 'name' => string '1.jpg' (length=5)
public 'tempName' => string 'D:\wamp\tmp\php8E46.tmp' (length=23)
public 'type' => string 'image/jpeg' (length=10)
public 'size' => int 77593
public 'error' => int 0
1 =>
object(yii\web\UploadedFile)[46]
public 'name' => string '2.jpg' (length=5)
public 'tempName' => string 'D:\wamp\tmp\php8E56.tmp' (length=23)
public 'type' => string 'image/jpeg' (length=10)
public 'size' => int 74896
public 'error' => int 0
2 =>
object(yii\web\UploadedFile)[47]
public 'name' => string '3.jpg' (length=5)
public 'tempName' => string 'D:\wamp\tmp\php8E57.tmp' (length=23)
public 'type' => string 'image/jpeg' (length=10)
public 'size' => int 72436
public 'error' => int 0

Categories