How to fix the "Undefined variable" error in Yii2 view? - php

Here is my controller:
class RoomController extends Controller
{
public function actionCreate()
{
$model = new Room();
$modelSave = false;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
}
return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);
}
}
and here is my view
<?php if($modelSave) { ?>
<div class = "alert alert-success" >
Model ready to be saved!
</div>
<?php } ?>
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class = "col-lg-12">
<h1>Room Form</h1>
<?= $form->field($model,'floor')->textinput()?>
<?= $form->field($model,'room_number')->textinput() ?>
<?= $form->field($model,'has_conditioner')->checkbox() ?>
<?= $form->field($model,'has_tv')->checkbox() ?>
<?= $form->field($model,'has_phone')->checkbox() ?>
<?= $form->field($model,'available_form')->textinput() ?>
<?= $form->field($model,'price_per_day')->textinput() ?>
<?= $form->field($model,'description')->textarea() ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('create',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
when i checked whether if it working,
the ErrorException shows:
PHP Notice – yii\base\ErrorException
Undefined variable: modelSave
I've tried to debug, but I have no idea why the $modelSave can't send to the view "create".

You test
<?php if($modelSave) { ?>
but in your render you have
return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);
use
<?php if($modelSaved) { ?>

You don't call the variable by its name, you should try to check $modelSaved since this is the name you give it
replace
<?php if($modelSave) { ?>
by
<?php if($modelSaved) { ?>

Related

Yii Recoverable error "Object of class **** could not be converted to string"

In my web application I have two models namely "ProducerOffer" and "Vegetable".I need to create an object of "ProducerOffer" inside "Vegetable " model view action.I need to create an object of "ProducerOffer" model inside "Vegetable" model.But I am geting this error and unable to trace the source.
The error I am getting
Object of class ProducerOffer could not be converted to string
The code I wrote in Vegetable Controller
public function actionCreateOffer($id)
{
$model=$this->loadModel($id);
$ProducerOffer=new ProducerOffer;
if(isset($_POST['ProducerOffer'])AND (isset($_POST['Vegetable'])) )
{
$ProducerOffer->attributes=$_POST['ProducerOffer'];
$model->attributes=$_POST['Vegetable'];
$ProducerOffer->vegetable_id=$model->id;
if($model->validate() AND $ProducerOffer->validate()) {
$model->save();
$ProducerOffer->save();
}
if (($model->hasErrors() === false)&&($ProducerOffer->hasErrors()===false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('offer',array('ProducerOffer'=>$ProducerOffer,'model'=>$model));
}
The code I wrote for my view named "offer.php".
<div style='padding-left:50px'>
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array('id'=>'non-ajax_form','enableAjaxValidation'=>false,)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model,$ProducerOffer); ?>
<b><?php echo CHtml::encode($model->getAttributeLabel('name')); ?>:</b>
<?php echo CHtml::textField("Vegetable[name]",$model->name); ?>
<b><?php echo CHtml::encode($ProducerOffer->getAttributeLabel('offered_qty')); ?>:</b>
<?php echo CHtml::textField("ProducerOffer[offered_qty]",$ProducerOffer->offered_qty); ?>
<?php echo CHtml::encode($ProducerOffer->getAttributeLabel('unit_cost')); ?>
<?php echo CHtml::textField("ProducerOffer[unit_cost]",$ProducerOffer->unit_cost); ?>
<?php echo CHtml::encode($ProducerOffer->getAttributeLabel('unit_delivery_cost')); ?>
<?php echo CHtml::textField("ProducerOffer[unit_delivery_cost]",$ProducerOffer->unit_delivery_cost); ?>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=> 'Save',)); ?>
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'reset', 'type'=>'primary', 'label'=> 'Reset')); ?>
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'link', 'type'=>'primary', 'label'=> 'Cancel','url'=>Yii::app()->user->returnUrl,)); ?>
</div>
<?php $this->endWidget(); ?>
</div>
My relation function in the ProducerOffer model
public function relations()
{
return array(
'producerOfferVegetableRelation' => array(self::BELONGS_TO, 'Vegetable', 'vegetable_id'),
}
My relation function in vegetable model
public function relations()
{
return array(
'producerOfferRelation'=> array(self::BELONGS_TO, 'Vegetable', 'id'),
);
}
I am unable to figure out the source of error ? How should I resolve this?
I am getting error in this lines as shown by the browser
<?php echo $form->errorSummary($model,$ProducerOffer); ?>
In the controller
$this->render('offer',array('ProducerOffer'=>$ProducerOffer,'model'=>$model));
I am getting error in these lines.
Error might be at this line:
<?php echo $form->errorSummary($model,$ProducerOffer); ?>
The second argument of this method is string $header but you are passing $ProducerOffer instead.
Change it like this:
<?php echo $form->errorSummary(array($model, $ProducerOffer)); ?>
or like this:
<?php echo $form->errorSummary($model); ?>
<?php echo $form->errorSummary($ProducerOffer); ?>
(try it yourself, I don't remember exactly is it possible to pass array of models as a first argument)

Yii: How to update multiple models using only 1 form 1 model and 1 action?

I have a model website and a model url.
Each url data is attached to a website data. A url is related to a website via a website_id.
On my web app, I need to check the data before accepting it.
I want to see on screen the entire data regarding a url data and I managed to do this.
Now, I also want to update the entire data that is listed on screen.
On screen I have the entire url data and website data, but when I try to save the data, the website data is empty.
My logic was to add to the url model a property: public $website;
And within the url model, a method aftersave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
//echo '<pre>';
//print_r($w);
print_r($this->website);
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save(false);
die;
return parent::afterSave();
}
and here is the important code from the _form file:
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
There are few questions:
Is the relation url and website being defined in the model such that $url->website of a existing url gives you valid website record?
You form shows, you are not using any website_id, means that you are creating a new website record for every URL, means $w = Website::model()->findByAttributes(array('id' => $this->website_id)); will always return NULL
I assume you have defined a relation of website within your URL model.
Suggested function from my understanding:
protected function afterSave() {
//data is already assigned by the caller
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
Yii::log("updating existing website data","info");
$this->website->save();
}
else
{
Yii::log("creating new website data","info");
$this->website->save();
$this->website_id = $this->website->website_id;
$this->update(array('website_id')); //save the relation
Yii::log("created new website {$this->website_id}","info");
}
return parent::afterSave();
}
It turned out to be small mistakes like w instead of W, object property instead of array;
Ok, so let me teach you how to do this;
I have 2 models: Url and Website.
Url model has a foreign key website_id and a relation to model Website;
Within the Url model I have a property called website and i declared it like: public $website = array();;
The data gets added thru a bookmarklet that uses a API so the data will be there when the admin comes to update/check it;
In the Url model i have a method afterSave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save();
}
return parent::afterSave();
}
where $this->website gets populated in the UrlController on actionUpdate like:
public function actionUpdate($id, $type = 'update') {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Url'])) {
$model->attributes = $_POST['Url'];
$model->website = $_POST['Website'];
if ($model->save())
if ($type == 'update')
$this->redirect(array('view', 'id' => $model->id));
else
$this->redirect(array('/admin/url/approvePublicLink'));
}
$model_website = Website::model()->findByAttributes(array('id'=>$model->website_id));
$this->render('update', array(
'model' => $model,
'model_website' => $model_website,
));
}
and gets passed to the afterSave method later;
this is the _update view:
<div style="padding:20px 20px;">
<h1>Update Url, Website, Keywords ...</h1>
<?php echo $this->renderPartial('_form', array(
'model'=>$model,
'model_website' => $model_website,
)); ?>
</div>
and this is the _form view that gets rendered partial:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'url-form',
'enableAjaxValidation'=>false,
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'website_id'); ?>
<?php echo CHtml::link($model->relation_website->domain,$model->relation_website->domain,array('class'=>'avia','target'=>'_blank')); ?>
<?php echo $form->error($model,'website_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'link'); ?>
<?php echo $form->textField($model,'link',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'important'); ?>
<?php echo $form->dropDownList($model,'important',array(0=>'Normal',1=>'Important')); ?>
<?php echo $form->error($model,'important'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'views'); ?>
<?php echo $form->textField($model,'views'); ?>
<?php echo $form->error($model,'views'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'created'); ?>
<?php echo $model->created; ?>
<?php echo $form->error($model,'created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'updated'); ?>
<?php echo $model->updated; ?>
<?php echo $form->error($model,'updated'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model,'status',array(-1=>'Banned',0=>'Normal',1=>'Active')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I hope it helps.

issues validation using render partial yii framework

I am loading a view using renderpartial, but the validations not working and not show the error messages. I tried to resolve the problem actived processOUtput in renderpartial but isn´t work.
this is my index view where I load the form view
<?php echo CHtml::link('Crear Usuario', array('create'), array('id'=>'newUsuario')); ?>
<div id="modal" class="modal hide fade"></div>
<script>
$(document).ready(function() {
$("#newUsuario").click(function() {
event.preventDefault();
$("#modal").load($("#newUsuario").attr("href"));
$("#modal").modal({show:true});
});
});
</script>
This is my action that load the view
public function actionCreate() {
$model = new Usuarios;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Usuarios']))
{
$model->validate();
$model->attributes=$_POST['Usuarios'];
$_POST['Usuarios']['check_tipo'] == 1 ? $model->tipo = 'Administrador' : $model->tipo = 'Normal';
$model->pass_php = md5($model->pass);
$model->session = $model->generateSalt();
$model->pass_hash= $model->hashPassword($_POST['Usuarios']['pass'], $model->session);
$this->transaction = $model->dbConnection->beginTransaction();
try {
if($model->save()) {
$this->transaction->commit();
$this->actionIndex();
}
} catch(Exception $e) {
$this->transaction->rollBack();
}
}
$this->renderPartial('create', array('model'=>$model));
}
And this is the view with the form
<h4 align="center">Nuevo Usuario</h4>
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'usuarios-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su email')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'check_tipo'); ?>
<?php echo $form->checkBox($model,'check_tipo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nombre'); ?>
<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su nombre')); ?>
<?php echo $form->error($model,'nombre'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pass'); ?>
<?php echo $form->passwordField($model,'pass',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su contraseña')); ?>
<?php echo $form->error($model,'pass'); ?>
</div>
</div>
<center>
<?php echo CHtml::button('Close', array('class'=>'btn', 'data-dismiss'=>'modal', 'aria-hidden'=>true)); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save', array('class'=>'btn btn-primary')); ?>
</center>
<?php $this->endWidget(); ?>
When I used render the validations and error messages work, the problem is just with renderpartial.
Help me please and sorry if my english is bad.

CForm and its behaviors do not have a method or closure named "beginWidget"

I am quite new in using Yii Fraework and I am trying to implement a custom form with the skeletron from the contact form demo withon the blog demo from Yii Framework. I did almost exactly the same view,, controller and model as the respective form, only that I get the following 500 error:
Error 500
CForm and its behaviors do not have a method or closure named "beginWidget".
Here are the : Controller:
<?php
class CustomController extends Controller {
public function actionSubmit()
{
$model = new CustomForm;
$form = new CForm('application.views.custom._form', $model);
$this->pageTitle = "ffffffffffff";//['title'] = "Authentication";
if($form->submitted('submit') && $form->validate())
$this->redirect(array('blog/index'));
else
$this->render('_form', array('form'=>$form));
}
public function getGenders()
{
return array(
0 => 'Male',
1 => 'Female');
}
}
?>
The Model:
<?php
class CustomForm extends CFormModel {
public $firstName;
public $LastName;
public $phone;
public $address;
public $gender;
public $email;
public function rules()
{
return array(
array('firstName, lastName, gender', 'required'),
array('email', 'email')
);
}
}
?>
The view:
<?php
$this->pageTitle=Yii::app()->name . ' - Custom Form';
$this->breadcrumbs=array(
'Custom Form',
);
?>
<h1>Custom Form</h1>
<?php if(Yii::app()->user->hasFlash('custom')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('custom'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'custom-form',
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'firstName'); ?>
<?php echo $form->textField($model,'firstName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'phone'); ?>
<?php echo $form->textField($model,'phone',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'gender'); ?>
<?php echo $form->radioButton($model,'gender',array('value'=>'Male')) . 'Male'; ?>
<?php echo $form->radioButton($model,'gender',array('value'=>'Female')) . 'Female'; ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'address'); ?>
<?php echo $form->textArea($model,'address',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Any ideas why am I getting this error? What am I doing wrong?
Thanks!
CForm represents a form object that contains form input specifications.
You are passing a view file as parameter to the CForm which wont work.
I guess there is no need for this line:
$form = new CForm('application.views.custom._form', $model);
Please check if it works :)

yii blog comment model with multimodel form

I would like to take the blog comment model and turn the form into a mulitimodel form but I have not been able to work this out. Would appreciate if anyone could point me in the right direction.
Taken the design below I want to add another table (OtherModel) off of comment with a FK in comment linking the tables.
Controller
public function actionView()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
));
}
protected function newComment($post)
{
$comment=new Comment;
$otherModel=new OtherModel;
if(isset($_POST['Comment'], $_POST['OtherModel']))
{
$comment->attributes=$_POST['Comment'];
$otherModel->attributes=$_POST['OtherModel'];
if($post->addComment($comment))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you...');
$this->refresh();
}
}
return $comment;
}
model
public function addComment($comment)
{
$comment->other_id=$otherModel->other_id;
$otherModel->save();
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
}
render form through CJuiTabs
'Comment'=>$this->renderPartial('/comment/_form',array($model->$comment=>),true)
form
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'author'); ?>
<?php echo $form->textField($model,'author',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,'author'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'content'); ?>
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'content'); ?>
</div>
// added otherModel as part of MMF
<div class="row">
<?php echo $form->labelEx($otherModel,'name'); ?>
<?php echo $form->textField($otherModel,'name',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($otherModel,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($otherModel,'description'); ?>
<?php echo $form->textArea($otherModel,'description',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($otherModel,'description'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Submit' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I think you have a mistake in your code given above: you are trying to use $otherModel variable instead of $comment rendered by your actionView() method.
Have you tried to use examples posted on yiiframework.com? I mean the link you've given in comment to your question. If it does not suit you, I afraid I've misunderstood your question.
I think you should validate both models before saving, otherwise you'd end up with a stale $otherModel record in your database.
protected function newComment($post)
{
$comment=new Comment;
$otherModel=new OtherModel;
if(isset($_POST['Comment'], $_POST['OtherModel']))
{
$comment->attributes=$_POST['Comment'];
$otherModel->attributes=$_POST['OtherModel'];
// also specify $otherModel as a param
if($post->addComment($comment, $otherModel))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you...');
$this->refresh();
}
}
return $comment;
}
public function addComment($comment, $otherModel)
{
// Validate both models, return false if there are errors.
// Errors should be available via $model->getErrors()
if ($comment->validate() && $otherModel->validate()) {
// save the otherModel first to obtain the generated ID
$otherModel->save();
$comment->other_id=$otherModel->id;
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
} else {
return false;
}
}
Note: You may also use transactions here.

Categories