php yii send error to form on actionCreate - php

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>

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/>')
);

yii - insert data into two tables via single form

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..

validate fields from diffrent models in a single form

I have the form
TblRegistration/_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tbl-registration-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,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary(array($model,$model1)); ?>
<div class="row">
<?php echo $form->labelEx($model,'director'); ?>
<?php echo $form->textField($model,'director',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'director'); ?>
</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">
<?php echo $form->labelEx($model,'language'); ?>
<?php echo $form->textField($model,'language',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'language'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model1,'email'); ?>
<?php echo $form->textField($model1,'email'); ?>
<?php echo $form->error($model1,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model1,'password'); ?>
<?php echo $form->textField($model1,'password'); ?>
<?php echo $form->error($model1,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
My actioncreate create contain
public function actionCreate()
{
$model=new TblRegistration;
$model1=new TblLogin();
// Uncomment the following line if AJAX validation is needed
//$this->performAjaxValidation($model1);
if(isset($_POST['TblRegistration']) && isset($_POST['TblLogin']))
{
$model->attributes=$_POST['TblRegistration'];
$model1->attributes=$_POST['TblLogin'];
$model->save();
if($model->save())
{
$model1->reg_id=$model->reg_id;
$model1->save();
}
if(($model->save() )&& ($model1->save()))
$this->redirect(array('view','id'=>$model->reg_id));
}
$this->render('create',array(
'model'=>$model,
));
}
my fields email and password is from the model TblLogin.I want to validate those fields before iam saving the data.how can i achive this?
After:
$model->attributes=$_POST['TblRegistration'];
$model1->attributes=$_POST['TblLogin'];
Add:
if($model->validate() && $model1->validate()){
$model->save();
...

Insert data in two different tables from single Controller in Yii

I have two different table and i want to insert data in both of them at a time.
ONE table is verse
verse(id, topic_id, surah_id, verse_text) // id is primary key,
Second table is verse_translations
verse_translations(id, verse_id, language_id, translations_text) // id is primary key, language_id is foreign key references with language table, // verse_id is foreign key references with verse table.
Verse Create File (_form.php)
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array('id'=>'verse-form', 'enableAjaxValidation'=>true)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'verse_text'); ?>
<?php echo $form->textArea($model, 'verse_text', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'verse_text'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'verse_translations'); ?>
<p class="<?php echo "tran".$model->id ?>">
<?php
$errors = array_filter($model->verseTranslations);
if(!empty($errors)) {
foreach($model->verseTranslations as $vt) {
echo $form->textArea($model, 'translation_text', array('value'=>$vt['translation_text'], 'rows'=>6, 'cols'=>50));
}
}
?>
</p>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
As you may see from _form file, I have called the data from verse_translations table.
Now my questions are:
How I keep the value of textArea that it will go in an array in controller? And How can I insert data in verse_translation table from verse create controller.
The output of _form file is like that.
Verse Create Controller Code.
public function actionCreate()
{
$model=new Verse;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Verse']))
{
$model->attributes=$_POST['Verse'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
Hope you understand it clearly.
Thanks
I think you should try this
public function actionCreate()
{
$verse_model=new Verse;
$verse_translation_model=new Verse_translations;
if(isset($_POST['Verse']) && isset($_POST['Verse_translations']))
{
$verse_model->attributes=$_POST['Verse'];
$verse_translation_model->attributes=$_POST['Verse_translations'];
$verse_model->save();
$verse_translation_model->save();
echo 'data is saved in both tables';
}
$this->render('create',array('verse_model'=>$verse_model,'verse_translation_model'=>$verse_translation_model));
}
In views in create.php
$this->renderPartial('_form',array('verse_model'=>$verse_model,'verse_translation_model'=>$verse_translation_model));
in _form.php
<?php $form = $this->beginWidget('CActiveForm', array('id'=>'verse-form', 'enableAjaxValidation'=>true)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($verse_model, 'verse_text'); ?>
<?php echo $form->textArea($verse_model, 'verse_text', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_model,'verse_text'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($verse_model, 'topic_id'); ?>
<?php echo $form->textArea($verse_model, 'topic_id', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_model,'topic_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($verse_model, 'surah_id'); ?>
<?php echo $form->textArea($verse_model, 'surah_id', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_model,'surah_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($verse_transaction_model, 'verse_id'); ?>
<?php echo $form->textArea($verse_transaction_model, 'verse_id', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_transaction_model,'verse_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($verse_transaction_model, 'translations_text'); ?>
<?php echo $form->textArea($verse_transaction_model, 'translations_text', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_transaction_model,'translations_text'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($verse_transaction_model, 'language_id'); ?>
<?php echo $form->textArea($verse_transaction_model, 'language_id', array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($verse_transaction_model,'language_id'); ?>
</div>
To store in two tables (Model), you have to create two model object for each.
for ex:
$v_model = new Verse; // For save function
$vt_model = new VerseTransctions; // For save function
Pass these model object to view file and use as below.
For verse model text boxes, you have to use:
labelEx($v_model, 'verse_text');
For verse_tarnsction model text boxes, you have to use:
labelEx($vt_model, 'translation_text');
In action (save / update):
$v_model->attributes = $_POST["Verse"];
if($v_model->save())
{ $vt_model->attributes = $_POST["VerseTransctions"];
$vt_model->verse_id = $v_model->id; $vt_model->save();
}

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.

Categories