yii - insert data into two tables via single form - php

I am very much a novice with PHP and the Yii framework.
Click here to see a sample of my SQL database setup http://i.stack.imgur.com/W6qQj.png
I have set up controllers and models for all three tables and have set up CRUD views from Gii for the Users table. I have read through this -> http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/ and tried multiple sets of code examples etc... and failed. The best I can do is get the create form to insert all the data into the users table but not the email table. I believe my short coming is in my UsersController.php -> public function actionCreate() section. Can someone help me out with a sample piece of code to make the information post into the email table?
---EDIT---
As requested below is the requested info...
UsersController.php
public function actionCreate()
{
$model = new Users;
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
$model->password=crypt($model->password,'salt');
$model->datecreated = new CDbExpression('NOW()');
if ($model->save()) {
$modelEmail = new Email;
$modelEmail->attributes = $_POST['Email'];
$modelEmail->fer_users_id = $model->id;
if ($modelEmail->save())
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This is the users/_form.php view file:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-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,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>255)); ?>
<?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>
<div class="row">
<?php echo $form->labelEx($model,'firstname'); ?>
<?php echo $form->textField($model,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastname'); ?>
<?php echo $form->textField($model,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(Email::model(),'emailaddress'); ?>
<?php echo $form->textField(Email::model(),'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error(Email::model(),'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($model, 'fer_roles_id',
CHtml::listData(Roles::model()->findAll(), 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>

you could do this:
Controller:
<?php
public function actionCreate()
{
$model = new Users;
$model1 = new Email;
$roles = Roles::model()->findAll();
if(isset($_POST['Users']))
{
$model->attributes = $_POST['Users'];
$model->password = crypt($model->password, 'salt');
$model->datecreated = new CDbExpression('NOW()');
$model->save();
$model1->attributes = $_POST['Users']['emailaddress'];
$model1->fer_users_id = $model->id;
$model1->save();
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('create', array(
'user'=>$model,
'email'=>$model1,
'roles'=> $roles
));
}
?>
your view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($user); ?>
<div class="row">
<?php echo $form->labelEx($user,'username'); ?>
<?php echo $form->textField($user,'username',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'password'); ?>
<?php echo $form->passwordField($user,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'firstname'); ?>
<?php echo $form->textField($user,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'lastname'); ?>
<?php echo $form->textField($user,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($email,'emailaddress'); ?>
<?php echo $form->textField($email,'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($email,'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($user, 'fer_roles_id',
CHtml::listData($roles, 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
if you get any error with this, let me know..

Related

Error when trying to store the id of the multiple checkbox in database in yii

I had multiple check box to view the Hobby names from database, and it's working. But i need to store the selected id of the hobby names in the database. But when i select any hobby name it stores only 0 in my database table.
I had one Hobbies table and i created one model for that also. Please anybody help.
This is in views/sample/register.php file
<?php
/* #var $this SampleController */
/* #var $model Sample */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'sample-register-form',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
'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,'username');
echo $form->textField($model,'username');
echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email');
echo $form->textField($model,'email');
echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password');
echo $form->passwordField($model,'password');
echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'confirm password');
echo $form->passwordField($model,'password');
echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'address');
echo $form->textArea($model,'address',array('rows'=>6, 'cols'=>22));
echo $form->error($model,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/Substate'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array('prompt'=>'Select Country First'),
array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/Subcity'),
'update'=>'#city_name',
'data'=>array('state_id'=>'js:this.value' ))));
echo $form->error($model,'state_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'city_id');
echo CHtml::dropDownList('city_name','', array('prompt'=>'Select State First'));
echo $form->error($model,'city_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'url');
echo CHtml::activeFileField($model, 'url'); // by this we can upload image
echo $form->error($model,'url'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'hobby');
//echo $form->checkBoxList($model,'hobby',CHtml::listData(Hobbies::model()->findAll(),'hobby_id','hobby_name'));
$data = Hobbies::model()->findAll();
foreach($data as $button)
{
//echo $button->course_name;
echo $form->checkBox($model,'hobby');
echo $button->hobby_name .'<br>';
}
echo $form->error($model,'hobby'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'gender');
echo $form->radioButtonList($model,'gender',array('Male'=>'Male','Female'=>'Female'),array('labelOptions'=>array('style'=>'display:inline'), // add this code
'separator'=>' ',
) );
echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'dob');
$form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'dob',
'name'=>$model->dob,
'value'=>$model->dob,
'options'=>array('dateFormat'=>'yy-mm-dd',
'altFormat'=>'yy-mm-dd',
'changeMonth'=>'true',
'changeYear'=>'true',
'yearRange'=>'1600:3000',
// which shows for both textfield and button
//'showOn'=>'both',
// 'buttonText'=>'choose date'
),
'htmlOptions'=>array('size'=>'10')
));
echo $form->error($model,'dob');
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Register'); ?>
</div>
<?php $this->endWidget(); ?>
This is in controller/SampleController.php file
public function actionRegister()
{
$model=new Sample;
if(isset($_POST['Sample']))
{
$model->attributes=$_POST['Sample'];
if($model->validate())
{
$model->hobby = implode(",",$model->hobby);
if($model->save())
{
$this->redirect(array('site/login'));
}
return;
}
}
$this->render('register',array('model'=>$model));
}
If you view the html generated by your foreach loop you will see that all your checkboxes have the same name and id. As such only one of them will be present in the $_POST array since the name is used as the key.
To fix this change the name to an array:
echo $form->checkBox($model, 'hobby[]');
Alternatively you can use CActiveForm::checkBoxList as in your commented code and use template to style it:
template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated check box input tag while "{label}" will be replaced by the corresponding check box label.
echo $form->checkBoxList(
$model,
'hobby',
CHtml::listData(Hobbies::model()->findAll(), 'hobby_id', 'hobby_name'),
array('template' => '{input}{label}<br/>')
);

How to Update a field based on the submit button - Yii

I'm new to Yii framework. I have to create three buttons in my form (update.php). i.e. (Save, Approve, Reject). I'm using the following fields in my form.
<?php
/* #var $this MessageTemplateController */
/* #var $model MessageTemplate */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'message-template-form',
'enableAjaxValidation'=>false,
)); ?>
<?php
echo $form->errorSummary($model);
?>
<div class="row">
<?php //$model->ReviewedDate=date('Y-m-d H:i:s');?>
<?php echo $form->labelEx($model,'ReviewedDate'); ?>
<?php echo $form->textField($model,'ReviewedDate',array('value'=>'0000-00-00 00:00:00','readonly' => true)); ?>
<?php echo $form->error($model,'ReviewedDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'SmsText'); ?>
<?php echo $form->textArea($model,'SmsText',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'SmsText'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UpdatedDate'); ?>
<?php echo $form->textField($model,'UpdatedDate'); ?>
<?php echo $form->error($model,'UpdatedDate',array('value'=>date('Y-m-d H:i:s'),'readonly' => true)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Approved'); ?>
<?php echo $form->hiddenField($model, 'Approved'); ?>
<?php echo $form->error($model,'Approved'); ?>
</div>
<div class="row">
<div class="row">
<?php echo $form->labelEx($model_al, 'username'); ?>
<?php $identity=Yii::app()->user->name;?>
<?php echo $form->textField($model_al, 'username',array('value'=>$identity,'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'username'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'updatedtime'); ?>
<?php echo $form->textField($model_al, 'updatedtime',array('value'=>date('Y-m-d H:i:s'),'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'updatedtime'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'comments on approval/rejection'); ?>
<?php echo $form->textField($model_al, 'comments',array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'comments'); ?>
<div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save', array('name' => 'save')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Accept', array('name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('name' => 'reject')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Now I have created three buttons.There is a field called approved in the above form.
I want this actions to happen when i click on the following buttons :
1. Save - All fields have to be saved but not approved(keep it as default).
2. Accept - All fields have to be saved with Approved changing to 1 in database.
3. Reject - All fields have to be saved with Approved changing to 0 in database.
How can I do this.
EDit
I have added the following in my controller.
public function actionUpdate($id)
{
$model_mt=new Messagesintable;
$model_al=new AuditLogin;
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['MessageTemplate']) && isset($_POST['AuditLogin']))
{
$model->attributes=$_POST['MessageTemplate'];
list($name,$mobile,$email)=retrieve_persondetails($id);
if($model->save())
{
$model_al->attributes=$_POST['AuditLogin'];
if ($model_al->save())
$this->redirect(array('admin','id'=>$model->Id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
You can check whether which submit button is clicked with these conditions and write your action inside.
if($_POST) {
if (isset($_POST['Save'])) {
// your code here
}
if (isset($_POST['Accept'])) {
// your code here
}
if (isset($_POST['Reject'])) {
// your code here
}
}

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.

internal server Error when load ajax in yii

I had problem in loading Ajax , I knew that by got screanshot of request by
Tamper Data :
http://up.arabseyes.com/uploads/02_12_1213544389861.jpg
result was : internal server Error .
What is the problem in my code ?
View :
<?php
/* #var $this UsersController */
/* #var $model Users */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-index-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'الأسم الأول'); ?>
<?php echo $form->textField($model,'first_name'); ?>
<?php echo $form->error($model,'الأسم الاول'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'العائلة'); ?>
<?php echo $form->textField($model,'last_name'); ?>
<?php echo $form->error($model,'العائلة'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'كلمة المرور'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد كلمة المرور'); ?>
<?php echo $form->passwordField($model,'passwordconfirm'); ?>
<?php echo $form->error($model,'passwordconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البريد الإلكتروني '); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد البريد الإلكتروني'); ?>
<?php echo $form->textField($model,'emailconfirm'); ?>
<?php echo $form->error($model,'emailconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تاريخ الميلاد'); ?>
<?php
$this->widget(
'ext.jui.EJuiDateTimePicker',
array(
'model' => $model,
'attribute' => 'birth_date',
'language'=> 'en',//default Yii::app()->language
'mode' => 'date',//'datetime' or 'time' ('datetime' default)
'options' => array(
'dateFormat' => 'yy-mm-dd',
//'timeFormat' => '',//'hh:mm tt' default
),
)
);
?>
<?php echo $form->error($model,'birth_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'الجنس'); ?>
<?php echo chtml::activeDropDownList($model,'gender',$model->getStatusOption(),array('prompt'=>'أختر جنسك')
); ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البلد'); ?>
<?php
/*
echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ') ,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('current/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
*/
echo CHtml::activedropDownList($model,'country',$model->getcountry(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Register/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
?>
<?php echo $form->error($model,'country'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'المدينة'); ?>
<?php
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city','', array());
?>
<?php echo $form->error($model,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رمز الاتصال'); ?>
<?php echo $form->textField($model,'mobile_code'); ?>
<?php echo $form->error($model,'mobile_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رقم الجوال'); ?>
<?php echo $form->textField($model,'mobile_number'); ?>
<?php echo $form->error($model,'mobile_number'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('تسجيــــــــــــل'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller :
....
public function actionDynamiccities() /// call Ajax
{
$data=Cities::model()->findAll('country=:country_id',
array(':country_id'=>(int) $_POST['country']));
$data=CHtml::listData($data,'id','city_name_e');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
};
}
....
Thanks in Advance .

php yii send error to form on actionCreate

I have the following form which is being used to create new records
<?php
/* #var $this ComponentsController */
/* #var $model Components */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'components-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,'component_id'); ?>
<?php echo $form->textField($model,'component_id'); ?>
<?php echo $form->error($model,'component_id'); ?>
</div>
<div class="row">
<label class="required" for="FixedAsset_original_asset_number">
Asset Number
</label>
<input id="Components_original_asset_number" type="text" name="Components[original_asset_number]">
<?php //echo Chtml::textField('fixed_asset_id', FixedAsset::model()->FindByPk($model2->fixed_asset_id)->fixed_asset_id); ?>
</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,'manufacturer'); ?>
<?php //echo $form->textField($model,'manufacturer'); ?>
<?php $manufacturer = Manufacturers::model()->findAll(array("order"=>"name"));
$list = CHtml::listData($manufacturer, 'manufacturer_id', 'name');
echo $form->dropDownList($model,'manufacturer', $list,array());
?>
<?php echo $form->error($model,'manufacturer'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'medium'); ?>
<?php //echo $form->textField($model,'medium'); ?>
<?php $medium = Medium::model()->findAll();
$list = CHtml::listData($medium, 'medium_id', 'type');
echo $form->dropDownList($model,'medium', $list,array());
?>
<?php echo $form->error($model,'medium'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'version'); ?>
<?php echo $form->textField($model,'version',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'version'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'serial_no'); ?>
<?php echo $form->textField($model,'serial_no',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'serial_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'purchase_date'); ?>
<?php //echo $form->textField($model,'purchase_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id'=>'Components_purchase_date',
'name'=>'Components[purchase_date]',
//'value'=>CTimestamp::formatDate('d/m/Y',$item->validFrom),
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'purchase_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'disposal_date'); ?>
<?php //echo $form->textField($model,'disposal_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id'=>'Components_disposal_date',
'name'=>'Components[disposal_date]',
//'value'=>CTimestamp::formatDate('d/m/Y',$item->validFrom),
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'disposal_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'model'); ?>
<?php echo $form->textField($model,'model',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'model'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nol'); ?>
<?php echo $form->textField($model,'nol'); ?>
<?php echo $form->error($model,'nol'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I want to send an error to the field Components_original_asset_number on the form. How would I achieve this. In the controller function I am checking to see if it exists if not I want to display error on form or message. original asset number is part of a separate model which I am displaying on this form.
public function actionCreate()
{
$model = new Components;
$model_fixedAsset = new FixedAsset;
$model_comAsset = new ComAsset;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Components']))
{
$model->attributes=$_POST['Components'];
$fixedAssetId = null;
// Check if asset exist and get PK
if( $_POST['Components']['original_asset_number'] != "" ){
//print_r($_POST['Components']);
$criteria = new CDbCriteria;
$criteria->condition = "(original_asset_number = :original_asset_number)";
$criteria->params = array(":original_asset_number" => $_POST['Components']['original_asset_number'] );
$fixedAssetRow = FixedAsset::model()->find($criteria);
//print_r($fixedAssetRow);
if($fixedAssetRow){
$fixedAssetId = $fixedAssetRow->fixed_asset_id;
}
//echo $fixedAssetId;
}
if($fixedAssetId){
/*if($model->save())
$this->redirect(array('view','id'=>$model->component_id));*/
// Create com_asset record
}else{
//no asset found return error message to input corect asset number or create asset in navision and run php script to update mysql db
}
}
$this->render('create',array(
'model'=>$model,
'model_fixedAsset'=>$model_fixedAsset,
'model_comAsset'=>$model_comAsset,
));
}
You should add the 'original_asset_number' in your model as variable and set required validation rule. Then you can use the following line to set error
$model->addError('original_asset_number', " no asset found return error message to input corect asset number or create asset in navision and run php script to update mysql ");
Also, you use the following way to display the field and error.
<?php echo $form->errorSummary($model); ?>
or
<div class="row">
<?php echo $form->labelEx($model,'original_asset_number'); ?>
<?php echo $form->textField($model,'original_asset_number',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'original_asset_number'); ?>
</div>

Categories