Why i getting an error "Call to a member function formName() on a non-object" - yii

i try to save multilanguaged content
My About model
...
public function rules() {
return [
[['status', 'date_update', 'date_create'], 'integer'],
[['date_update', 'date_create'], 'required'],
];
}
...
public function getContent($lang_id = null) {
$lang_id = ($lang_id === null) ? Lang::getCurrent()->id : $lang_id;
return $this->hasOne(AboutLang::className(), ['post_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
My AboutLang model
public function rules()
{
return [
[['post_id', 'lang_id', 'title', 'content'], 'required'],
[['post_id', 'lang_id'], 'integer'],
[['title', 'content'], 'string'],
];
}
My About controller
public function actionCreate()
{
$model = new About();
$aboutLang = new AboutLang();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,'aboutLang'=>$aboutLang]);
}
}
and my view (create form)
...
<?= $form->field($model, 'status')->textInput() ?>
<?= $form->field($aboutLang, 'title')->textInput() ?>
<?= $form->field($aboutLang, 'content')->textInput() ?>
enter code here
And when i put $aboutLang in create form i get an error "Call to a member function formName() on a non-object"

It looks like the views you are using were generated by Gii. In that case, Gii generates a partial view for the form (_form.php) and two views both for create and update actions (create.php and update.php). These two views perform a rendering of the partial view.
The problem you might have is that you are not passing the variable $aboutLang from create.php to _form.php, that must be done in create.php, when you call renderPartial():
$this->renderPartial("_form", array(
"model" => $model,
"aboutLang" => $aboutLang, //Add this line
));
Hope it helps.

Check your $aboutLang type.
It looks like it is null.
if ($aboutLang) {
echo $form->field($aboutLang, 'title')->textInput();
echo $form->field($aboutLang, 'content')->textInput();
}

Related

Yii2 - Bad Request (#400) Missing required parameters in index.php

I have problem for action view, update, and delete in index.php page, it always show bad request (#400) Missing required parameters: id_kategori and the address always go to localhost/training/frontend/web/index.php?r=kategori%2F(view/update/delete)&id=1, but when i change the address manually to localhost/training/frontend/web/index.php?r=kategori%2Fview&id_kategori=1 it's no problem, also i can create action but then it will redirect page to localhost/training/frontend/web/index.php?r=kategori%2Fview&id=1. Here's the code, its generate from Gii CRUD:
public function actionView($id_kategori)
{
return $this->render('view', [
'model' => $this->findModel($id_kategori),
]);
}
public function actionUpdate($id_kategori)
{
$model = $this->findModel($id_kategori);
if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
return $this->redirect(['view', 'id_kategori' => $model->id_kategori]);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionDelete($id_kategori)
{
$this->findModel($id_kategori)->delete();
return $this->redirect(['index']);
}
Should i rename id_kategori column to id and other id_column just to id?
Version: Yii 2 (2.0.43)
Template: Advanced Template
define $id_kategori=null in function
public function actionView($id_kategori=null)
{
return $this->render('view', [
'model' => $id_kategori ? $this->findModel($id_kategori) : null,
]);
}
You need to do like this
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}

PHP Recoverable Error – yii\base\ErrorException Object of class yii\web\Response could not be converted to string

I use renderPartial to view CRUD in my frontend/index.php. but its giving error
PHP Recoverable Error – yii\base\ErrorException
Object of class yii\web\Response could not be converted to string
here is code C:\xampp\htdocs\yii2-my-app\frontend\views\site\index.php
<?= Yii::$app->runAction('/callback/create'); ?>
C:\xampp\htdocs\yii2-my-app\frontend\controllers\CallbackController.php
public function actionCreate()
{
$model = new Callback();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->renderPartial('create', [
'model' => $model,
]);
}
}
how to fix that error can anybody help?
public function actionCreate()
{
$model = new Callback();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model = new Callback();
return $this->renderPartial('create', [
'model' => $model,
]);}
}

yii2 Dimensions to be validated and display the error message in the form

In yii2 project I have my own file structure setup. Anything uploaded will get saved as a file type. I can get the file dimensions using the file uploaded in the temp folder by yii2. Using those dimensions I set my own width and height and compare them. If the height and width is more than what I have declared It has display an error message in the form. Which I am unable to do it.
My Active Form
<div class="company-form">
<?php
$form = ActiveForm::begin([
'action'=>['company/logo', 'id'=>$model->company_id],
'validateOnSubmit' => true,
'options' =>
['enctype' => 'multipart/form-data','class' => 'disable-submit-buttons','id'=> 'companyLogoForm'],
'fieldConfig' => [
'template' => "<div class=\"row\">
<div class=\"col-xs-6 margin-top-8\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
\n<div class=\"col-xs-12 \">{input}</div>
</div>",
],
]); ?>
<?= $form->errorSummary($model, $options = ['header'=>'','class'=>'pull-left']); ?>
<?= $form->field($model, 'company_name')->hiddenInput(['maxlength' => true])->label(false) ?>
<?= $form->field($file, 'file')->fileInput([])->label(Yii::t('app', 'Attach Logo'),['class'=> 'margin-top-8']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Save') : Yii::t('app', 'Save'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary','data' => ['disabled-text' => 'Please Wait']]) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My Controller Action
public function actionLogo($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = new File;
$file->load(Yii::$app->request->post());
$a = UploadedFile::getInstance($file,'file');
$size = getimagesize($a->tempName);
$maxWidth = 500;
$maxHeight = 500;
if ($size[0] > $maxWidth || $size[1] > $maxHeight)
{
$model->addError('file', $error = 'Error Message');
if($model->hasErrors()){
return ActiveForm::validate($model);
}
}
$file->file = UploadedFile::getInstance($file,'file');
$file->file_name = $file->file->name;
$file->file_user = Yii::$app->user->id;
$file->file_type = 1;
if($file->save()){
$file->file_path = Files::getFilePath($file->file_id);
$validDir = $file->file->createFileDir($file->file_path, $file->file_id);
if($validDir){
$file->file->saveAs($file->file_path, false);
if($file->save()){
$model->company_file = $file->file_id;
$model->save();
return $this->redirect(['index']);
}
}
}
}
}
How do I add error message in the controller and pass that to display on my form on the modal box.
Note: my form is displayed on the modal box.
Thank you!!
You should handle the file processing in your model - or even better, create a specific UploadForm model for this purpose.
In that case you can use File Validation or a custom validator to set errors during model validation.
The built-in yii\validators\FileValidator gives you plenty pf validation rules out of the box.
This is actually pretty well explained in the documentation: Uploading Files
See also the documentation for FileValidator
Example for validating an uploaded image file:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
Try this validation rule
['imageFile', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250, 'extensions' => 'jpg, gif, png', 'maxSize' => 1024 * 1024 * 2],

default selected in multiselect dropdown in yii

it will not display default selected value in my multi select dropdown list and i am not getting the mistak. is dropdown list accept array for defalt select array list
public function actionCreate()
{
.......
$cust= implode('_',$_POST['supplier'] ['manufacture']);
$model->customer = $cust;
$model->save();
........
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->customer = explode('_',$model->customer);
if ($model->load(Yii::$app->request->post())) {
$cust= implode(',',$_POST['supplier']['manufacturer']);
$model->customer = $cust`enter code here`;
$model->save();
return $this->redirect(['view', 'id' => $model->ID]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
View
<?=
$form->field($model, 'car_manufacturer[]')->dropDownList($model->getcustinfo(), [
'multiple'=>'multiple',
'class'=>'chosen-select input-md required',
]);
?>
Pass the selected value in options:
['options' => $yourvalue => ['Selected'=>'selected']]
You should pass an array in options:
['options' =>
[
$id1 => ['selected' => true]
],
[
$id2 => ['selected' => true]
],
]
You can use foreach loop to make this array.
You should use only attribute name.
<?= $form->field($model, 'car_manufacturer')->dropDownList($model->getcustinfo(), [
'multiple'=>'multiple',
'class'=>'chosen-select input-md required', ])?>

`Skip on empty` not working in Yii2 file upload

I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading it again!
Here's my update form
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
.....
<?= $form->field($model, 'logo')->fileInput() ?>
...
My Controller action
if ($model->load($_POST) ) {
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
if($file){
$model->logo=$file; }
if($model->save()){
if($file)
$file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
}
return $this->redirect(['profile']);
} else {
return $this->renderPartial('update', [
'model' => $model,
]);
}
My Rules:
public function rules()
{
return [
[['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
[['name'], 'required'],
[['name', 'description'], 'string'],
];
}
Any ideas????
skipOnEmpty does not apply here because in the update action the $model->logo attribute will not be empty, it will be a string with the file name.$file is still an array with only keys, but not values if not uploaded again. So checked the $file->size instead of checking !empty($file). Fixed the issue by modifying the controller code as follows!
$model = $this->findModel($id);
$current_image = $model->featured_image;
if ($model->load(Yii::$app->request->post())) {
$image= UploadedFile::getInstance($model, 'featured_image');
if(!empty($image) && $image->size !== 0) {
//print_R($image);die;
$image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
$model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension;
}
else
$model->featured_image = $current_image;
$model->save();
return $this->redirect(['update', 'id' => $model->module_id]);
} else {
return $this->render('add', [
'model' => $model,
]);
}
'skipOnEmpty' => !$this->isNewRecord
For update it can be skipped.