display view page with data from two models in yii - php

I have two models Register and Login.I insert data into these two tables from a single form,I want to display the entered data in a single view page,ie data from two models in a single view.php.
RegisterController.php
public function actionCreate()
{
$model = new Register;
$modelLogin = new Login;
$modelGenerate = new Generate;
$row = Generate::model()->findByPk('1') ;
$gen_reg = $row['gen_reg'];
$gen_log = $row['gen_log'];
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['btnRegister']))
{
$model->attributes=$_POST['Register'];
$modelLogin->attributes=$_POST['Login'];
$modelLogin->reg_id=$model->reg_id;
$valid = $model->validate();
$valid = $modelLogin->validate() && $valid;
if($model->save()&& $modelLogin->save())
$this->redirect(array('view','id'=>$modelLogin->log_id)
);
}
$this->render('create',array(
'model'=>$model,
'modelLogin'=>$modelLogin,
'gen_reg'=>$gen_reg,
'gen_log'=>$gen_log
));
}
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'register-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
)); ?>
<div class="row">
<?php echo $form->textField($model,'reg_id',array('size'=>10,'maxlength'=>10,'class'=>'txt'));?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>50,'maxlength'=>50,'class'=>'txt')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'email'); ?>
<?php echo $form->textField($modelLogin,'email',array('size'=>60,'maxlength'=>100,'class'=>'txt')); ?>
<?php echo $form->error($modelLogin,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'password'); ?>
<?php echo $form->passwordField($modelLogin,'password',array('size'=>50,'maxlength'=>50,'class'=>'txt')); ?>
<?php echo $form->error($modelLogin,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'passwordCompare'); ?>
<?php echo $form->passwordField($modelLogin,'passwordCompare',array('size'=>60,'maxlength'=>64,'class'=>'txt')); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobile'); ?>
<?php echo $form->textField($model,'mobile',array('size'=>10,'maxlength'=>10,'class'=>'txt')); ?>
<?php echo $form->error($model,'mobile'); ?>
</div>
<div class="row">
<?php echo $form->textField($modelLogin,'log_id',array('size'=>10,'maxlength'=>10,'class'=>'txt'));?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Register' : 'Save',array('name'=>'btnRegister','class'=>'btn')); ?>
</div>
<?php $this->endWidget(); ?>
Relation in register model
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'logins' => array(self::HAS_MANY, 'Login', 'reg_id'),
);
}
Relation in login model
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'reg' => array(self::BELONGS_TO, 'Register', 'reg_id'),
);
}
I want to display data from two models(that i just inserted before)to be displayed on my view.php page.how can i achive this??? now i got the output as not set for fields from Login model.
view.php
$this->breadcrumbs=array(
'Register'=>array('index'),
$model->reg_id,
);
$this->menu=array(
array('label'=>'List Register', 'url'=>array('index')),
array('label'=>'Create Register', 'url'=>array('create')),
array('label'=>'Update Register', 'url'=>array('update', 'id'=>$model->reg_id)),
array('label'=>'Delete Register', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->reg_id),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Register', 'url'=>array('admin')),
);
?>
<h1>View Register #<?php echo $model->reg_id; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'reg_id',
'username',
'mobile',
),
)); ?>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$row,
'attributes'=>array(
'log_id',
'password',
'email',
),
)); ?>

Related

update form with database value in field

I'm newbie.I want to create update form in yii.I created a controller Adminprofile and call the model ProfileForm.In my view 'adminprofile.php' I want to load the value for the admin from the table 'superadmin' in name and password fields.Now It displays only field without values.
I want to use update as $update=update superadmin set username='$username',password='$password' where id='1'
SiteController.php
public function actionAdminprofile()
{
$model=new ProfileForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
$password='=?UTF-8?B?'.base64_encode($model->password).'?=';
$this->refresh();
}
}
$this->render('adminprofile',array('model'=>$model));
}
ProfileForm.php (MODEL)
class ProfileForm extends CFormModel
{
public $name;
public $password;
public function rules()
{
return array(
// name, email, subject and body are required
array('name, password', 'required'),
);
}
}
Adminprofile.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->textField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<?php endif; ?>

undefined variable model in yii

I am getting the error undefined variable model. I have the following codes in my view and controller. My aim is to search the results and show it in same page. I have tried the following things but its not working.
Again,I this this the conventional yii method to do so,or do I have to use a search() function from model SearchEmployee().?
public function actionSearch()
{
$model = new SearchEmployee();
/*Getting Data From Search Form For Processing */
if (isset($_POST['SearchEmployee'])) {
$category = $_POST['SearchEmployee']['category_id'];
$skills = $_POST['SearchEmployee']['skills'];
$experience = $_POST['SearchEmployee']['experience'];
$model = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND key_skills like '%$skills%' AND experience=$experience",
));
$this->render('search',$model);
}
/*Getting Data From Search Form For Processing */
$this->render('search', array('model' => $model));
}
In View Section: search.php//To display and search the desired result
<div class="row">
<?php echo $form->labelEx($model,'Category'); ?>
<?php echo $form->dropDownList($model,'category_id',$list,array('empty' =>'(Select a Category')); ?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Experience'); ?>
<?php echo $form->textField($model,'experience'); ?>
<?php echo $form->error($model,'experience'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<div class="view">
<h1>Results </h1>
<div class="view" id="id">
<h1> Records Display </h1>
<h4>Name: <?php echo $form->labelEx($model,'name'); ?></h4>
<h4>Skills: <?php echo $form->labelEx($model,'experience'); ?></h4>
<h4>Experience: <?php echo $form->labelEx($model,'skills'); ?></h4>
<h5> &nbsp ;<?php echo $form->labelEx('VIew Details'); ?></h5>
</div>
</div>
In view section I am using the search and view results option in the same form.I am getting the error after clicking the search button.Is this the correct way to do
$model = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND
key_skills like '%$skills%' AND experience=$experience",
));
There is error here. You can't use find in that way.
public function find($condition='',$params=array())
$model = SearchEmployee::model()->find("category_id=$category AND
key_skills like '%$skills%' AND experience=$experience");
But better
$model = SearchEmployee::model()->find("category_id=:category AND key_skills like :skill AND experience=:experience", array(
'category'=>$category,
'skill'=>'%'.$skills.'%',
'experience'=>$experience
));
Remove this line:
$this->render('search',$model);
First it's invalid because it should be:
$this->render('search', array('model' => $model));
But also it's unnecessary because you already have it lower in your code.

Setting default values and Creating into Database using Yii

I'm trying to create a new user but I'm having trouble trying to create the user because some of the values that are needed to create a user must be default values that I'm not quite sure how to set. I also need to input into a different table while the actual "create" happens from a different controller.
Here is my form code:
<?php
/* #var $this SystemUserController */
/* #var $model SystemUser */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'system-user-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,'party_id'); ?>
<?php echo $form->textField($model,'party_id',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'party_id'); ?>
</div>
!-->
<div class="row" id="toshow" style="display:none" name="suppliers"> <?php $supplier = SupplierHead::model()->findAll();
$list = CHtml::listData($supplier ,'head_id','head_name');
echo $form->DropDownList($model,'party_id',
$list, array('prompt'=>'Select Supplier')); ?>
</div>
<button id="abutton">Already a Supplier</button>
<script>
$(document).ready(function() {
$("#abutton").click(function(e){
e.preventDefault();
$("#toshow").css('display', 'block');
});
});
</script>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<script>
$("#supplier").click(function () {
$("#suppliers").show("slow");
});
</script>
<!--
<div class="row">
<?php echo $form->labelEx($model,'date_last_login'); ?>
<?php echo $form->textField($model,'date_last_login'); ?>
<?php echo $form->error($model,'date_last_login'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->textField($model,'status',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_created'); ?>
<?php echo $form->textField($model,'date_created'); ?>
<?php echo $form->error($model,'date_created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_modified'); ?>
<?php echo $form->textField($model,'date_modified'); ?>
<?php echo $form->error($model,'date_modified'); ?>
</div>
--!>
<div class="row">
<?php echo $form->labelEx($model,'user_role'); ?>
<?php echo $form->textField($model,'user_role',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'user_role'); ?>
</div>
<!--
<div class="row">
<?php echo $form->labelEx($model,'isLogin'); ?>
<?php echo $form->textField($model,'isLogin'); ?>
<?php echo $form->error($model,'isLogin'); ?>
</div>
--!>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
As you can see, I've commented out the attributes that I don't want to use. I also fixed the SystemUser model attributes rules() to define which attributes won't be needed for user input here:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('party_id, username, password', 'required'),
//array('isLogin', 'numerical', 'integerOnly'=>true),
array('party_id', 'length', 'max'=>20),
array('username', 'length', 'max'=>200),
array('password, user_role', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('party_id, username' 'on'=>'search'),
);
}
Finally, there's also a drop down list I included above from the form that is required to be inserted into a model of a different controller. How do I go about this?
The attributes that need default values are as follows:
date_last_login
status
date_created
date_modified
EDIT
I've uploaded a picture of what happens when I select "Create"
I decided not to add defaults try keeping them NULL just to see if the rules() would work. I
Any help?
Yii's model has methods such as:
beforeSave()
afterSave()
beforeValidate()
afterValidate()
and so on ...
which can be overridden into your model. If you want to set any default value before saving/validating you can use from mentioned methods in your model. Please take a look at the following example:
public function beforeSave() {
if (parent::beforeSave()) {
//Example
$this->date_modified=new New CDbExpression('NOW()');
//ANOTHER EXAMPLE
$this->date=date('Y-m-d',time());
// YOU CAN EVEN CALLING A WEBSERVICE
// ANYTHING THAT YOU WANT TO DO BEFORE SAVING INTO DATABASE
return true;
}
}
other methods such as afterSave and ... work like above.
I hope it help :)
You can use the rules for it like
public function rules()
{
return array(
// your other rules
array('myField','default','value'=>'my Name'),
// for date type use new CDbExpression('NOW()')
array('date_modified','default',
'value'=>new CDbExpression('NOW()'),
),
// rest of your rules
);
}
Try with this data type:
date_last_login : timestamp
status : enum('active','inactive')
date_created : timestamp
date_modified : timestamp
Defult Time stamp: current_timestamp

Validating a Form without redirect

I created app with yii and I need to load a view form in Fancy-box.
I did that but my problem is when I click on the submit button the form redirects me to the controller action without validating the form.
How to validate the form without the redirect inside Fancy-box?
My view:
<?php
$config = array(
);
$this->widget('application.extensions.fancybox.EFancyBox', array(
'target'=>'#getaction',
'config'=>$config,));
echo CHtml::link('Add Section',array('section/create'),array('id'=>'getaction'));
?>
FormView _from from call from another view
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'section-form',
'enableAjaxValidation'=>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,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller :
public function actionCreate()
{
$model=new Section;
if(isset($_POST['Section']))
{
$model->attributes=$_POST['Section'];
if($model->validate())
//// Do Som code here
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
the problem was fixed by my bro seenivasan on Yii Forum , so I will share the code here
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'section-form',
'enableAjaxValidation'=>true,
//'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true), //This is very important
)); ?>
<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,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>64)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
In controller
public function actionCreate()
{
$model=new Section;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);//You have enabled ajax validation. You have to uncomment this line.
if(isset($_POST['Section']))
{
$model->attributes=$_POST['Section'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
if(Yii::app()->request->getIsAjaxRequest())
echo $this->renderPartial('_form',array('model'=>$model),true,true);//This will bring out the view along with its script.
else $this->render('create',array(
'model'=>$model,
));
}
Reference link :
Yii Forum
Just add 'enableClientValidation'=>true, in the array inside the beginwidget.

yii manage sub table's data in form

I am working on YII framework, and I am a newbie.
I have user register form as shown below:
Username: [Textbox]
Email: [Textbox]
Address: [Text area]
User Loan Type: (Checkbox list as below)
Loan Type 1
Loan Type 2
Loan Type 3
Loan Type 4
Loan Type 5
Status [yes/no]
Now I have 3 models:
1) User (for user data)
2) LoanType (just for loan type list)
3) UserLoanType (mapping between user and loan type)
All 3 models have HAS_MANY and BELONGS_TO relations as we generally do in YII.
Now when user click on register button I want to save data in user_loan_type table as well. I can simply add core php logic in actionCreate. But is there any standard YII practice for this?? Because I need validation, remain form selected during edit etc. Can anyone guide me how to do this? Or point me any example link, I have googled but did't help.
Thanks.
I am able to save data in database,
Now during edit I want to retrieve 3rd table's(tbl_user_loan_request_type) data. I have used below code.
$user = User::model()->findByPk(5);
print_r($user->UserLoanTypes);
But it is giving me blank array.
Where I am wrong??
You may define afterSave methods in your class, like this:
Model User
public function relations()
{
return array(
'UserLoanTypes' => array(self::MANY_MANY, 'LoanType', 'UserLoanType(userId, loanId)'),
);
}
// relation
array('UserLoanTypes', 'safe'),
// label
'UserLoanTypes' => 'User Loan Type'
protected function afterSave()
{
parent::afterSave();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
foreach ($this->UserLoanTypes as $loanId) {
$userLoanType = new UserLoanType();
$userLoanType->userId = $this->id;
$userLoanType->loadId = $loadId;
$userLoanType->save();
}
}
protected function afterDelete()
{
parent::afterDelete();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
}
In form:
<div class="row">
<?php echo $form->labelEx($model,'UserLoanTypes'); ?>
<?php echo $form->checkBoxList($model,'UserLoanTypes', CHtml::listData($LoanTypes, 'id', 'loanName')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
In view you may:
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
'UserLoanTypes' => array(
'name' => 'UserLoanTypes',
'value' => implode(',', CHtml::listData($model->UserLoanTypes, 'id', 'name')),
),
),
)); ?>
If you don't need to assign multiple loanTypes to one User, it would be easier. All you need is the User model for the form visualization:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Username'); ?>
<?php echo $form->textField($model,'Username'); ?>
<?php echo $form->error($model,'Username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Email'); ?>
<?php echo $form->textField($model,'Email'); ?>
<?php echo $form->error($model,'Email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Address'); ?>
<?php echo $form->textArea($model,'Address'); ?>
<?php echo $form->error($model,'Address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UserLoanType'); ?>
<?php echo $form->checkBoxList($model,'idLoanType', CHtml::listData(LoanType::model()->findAll, 'id', 'name')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
<?php $this->endWidget(); ?>

Categories