Yii, CactiveForm saving multiples tables in DB - php

im new at yii and im trying to save datas in different tables on CactiveForm.. this is my code on view:
<?php
/* #var $this UserController */
/* #var $user User */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-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'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($user, $gunwcuser, $game, $cash); ?>
<div class="row">
<?php echo $form->labelEx($user,'user'); ?>
<?php echo $form->textField($user,'user',array('size'=>16,'maxlength'=>16)); ?>
<?php echo $form->error($user,'user'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'Gender'); ?>
<?php echo $form->radioButtonList($user,'Gender', array(0 => 'Male', 1 => 'Female'), array('labelOptions'=>array('style'=>'display:inline'), 'separator'=>' ',)); ?>
<?php echo $form->error($user,'Gender'); ?>
</div><br>
<div class="row">
<?php echo $form->labelEx($user,'NickName'); ?>
<?php echo $form->textField($user,'NickName',array('size'=>16,'maxlength'=>16)); ?>
<?php echo $form->error($user,'NickName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'Password'); ?>
<?php echo $form->passwordField($user,'Password',array('size'=>16,'maxlength'=>16)); ?>
<?php echo $form->error($user,'Password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'E_Mail'); ?>
<?php echo $form->textField($user,'E_Mail',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($user,'E_Mail'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'Country'); ?>
<?php echo $form->textField($user,'Country',array('size'=>3,'maxlength'=>3)); ?>
<?php echo $form->error($user,'Country'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
there are 4 tables in DB.. which are (user, gunwcuser, game, cash). This form is for user table, the gunwcuser is going to have the same data thats put in user form, but not all the data thats being saved on the form is being requested..
this is my controller:
public function actionCreate()
{
$user = new User;
$gunwcuser =new Gunwcuser;
$game = new Game;
$cash = new Cash;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$auth = 1;
$time = '0000-00-00 00:00:00';
if(isset($_POST['User']))
{
// Set data column in DB before saving
$user->Status = '1';
$user->MuteTime = $time;
$user->RestrictTime = $time;
$user->Authority = $auth;
$user->User_Level = '1';
$user->Authority2 = $auth;
$user->attributes=$_POST['User'];
$_POST['Gunwcuser'] = $_POST['User'];
$gunwcuser->Status = '1';
$gunwcuser->MuteTime = $time;
$gunwcuser->RestrictTime = $time;
$gunwcuser->Authority = $auth;
$gunwcuser->User_Level = '1';
$gunwcuser->Authority2 = $auth;
$gunwcuser->AuthorityBackup = $auth;
$gunwcuser->attributes=$_POST['Gunwcuser'];
$_POST['Game'] = $_POST['User'];
if($user->save())
$this->redirect(array('view','id'=>$user->Id));
}
$this->render('create',array(
'user'=>$user, 'gunwcuser'=>$gunwcuser, 'game'=>$game, 'cash'=>$cash,
));
}
i tried to copy the attributes from user to gunwcuser but when i save the data from user, i check on the DB to see if also gunwcuser has been saved but it wasnt..
theres also a few data thats going to be the same on game table but most of it, is going to be different, same as cash..
the common data are (id, username, nickname, gender, email, country, password)..
anyone can tell me how to save data in different tables on the same form? also saving different data on the same time

Hmm.. let's see. You have two models, but you save only one :). Add this code
$gunwcuser ->save()
before $this->redirect
if you wanna save both $user and $gunwcuser, You have to use save() method on each model object
if($user->save() && $gunwcuser ->save())
$this->redirect(array('view','id'=>$user->Id));

Related

Yii form submition with CActiveForm

i just need to do a registration form, i'm battling with completing this task with CActiveForm. Basically its just inserting a new db record on form submit. This is what i have,
MyView
<!--begin a form-->
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-registration-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'focus'=>array($model,'firstName'),
)); ?>
<!--error handling-->
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'firstName'); ?>
<?php echo $form->textField($model,'firstName'); ?>
<?php echo $form->error($model,'firstName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName'); ?>
<?php echo $form->error($model,'lastName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'age'); ?>
<?php echo $form->textField($model,'age'); ?>
<?php echo $form->error($model,'age'); ?>
</div>
<?php $this->endWidget(); ?>
<!--end a form-->
My Controller that renders the above view, this where i'm stuck, I also created a model called User(haven't done any code in it, default)
class RegisterController extends Controller
{
public function actionIndex()
{
$model = User::
$this->render('index', array('model'=>$model));
}
}
From my research i found there is something like, jst dnt know how to use it
link
$post=new Post;
$post->title='sample post';
$post->content='post body content';
$post->save();
Thanks in advance
You need to do in your actionIndex:
public function actionIndex()
{
$model = new User;
if(isset($_POST['User']))
{
$model->attributes = $_POST['User'];
if($model->save())
//Do any stuff here. for example redirect to created user view.
}
$this->render('index', array('model'=>$model));
}
I recommend you to read the Building a blog system with Yii tutorial. This is very good resource for learning yii better and also learn you the most important parts of any web application.

actionCreate being called multiple times - Yii

I'm running into a bug where my model is saving multiple times whenever I submit a gii-generated field. I've created an error log so that I can see what is being called multiple times, and I have found out that the function actionCreate is the part of my code that being called three times (Though sometimes two). When I fill out a form an click submit, the error log shows that the actionCreate function is being called three times.
The controller form looks like this
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Account;
error_log("How many times do I call actionCreate");
// To-Do make the user account creation update via ajax
// $this->performAjaxValidation($model);
if(isset($_POST['Account']))
{
$model->attributes=$_POST['Account'];
if($model->save())
{
echo 'do we reach here';
$this->redirect(array('index','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
My form, as well, looks like this
<?php
/* #var $this AccountController */
/* #var $model Account */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'account-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($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>40,'maxlength'=>40)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobile_comp'); ?>
<?php echo CHtml::dropDownList(CHtml::activeName($model,'mobile_comp'), $select,
$model->providerOptions, array('empty'=>'(Select Your Provider')); ?>
<?php echo $form->error($model,'mobile_comp'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'msisdn'); ?>
<?php echo $form->textField($model,'msisdn'); ?>
<?php echo $form->error($model,'msisdn'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pin'); ?>
<?php echo $form->textField($model,'pin'); ?>
<?php echo $form->error($model,'pin'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'company'); ?>
<?php echo $form->textField($model,'company',array('size'=>40,'maxlength'=>40)); ?>
<?php echo $form->error($model,'company'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'balance'); ?>
<?php echo $form->textField($model,'balance',array('size'=>40,'maxlength'=>40)); ?>
<?php echo $form->error($model,'balance'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
The error was in my form where I had ajaxValidation=>true instead of ajaxValidation=>false
I was accidentally calling the function ActionCreate multiple times with one field .
Becuase you've commented in line:
// To-Do make the user account creation update via ajax
// $this->performAjaxValidation($model);
Function $this->performAjaxValidation($model); validates form data if requested via Ajax and returns validation results as JSON and stops application execution ahead.
In your case if Ajax validation is happening then there is nothing to check for validation and problem is saving your model.
Just un-comment $this->performAjaxValidation($model);
ALSO: Please add code of function $this->performAjaxValidation($model)

how to assign array to $model in yii

Sorry. I was shorten my question because i was consider that, those users who work on yii can easily understand my question but now i am modifying so you can easily understand.
I want to update two different table at a time through single controller/view.
_form.php (update form)
<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>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'topic_id'); ?>
<?php echo $form->textField($model,'topic_id', $model->topic_id); ?>
<?php echo $form->error($model,'topic_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'sorah_id'); ?>
<?php echo $form->textField($model,'sorah_id', $model->topic_id); ?>
<?php echo $form->error($model,'sorah_id'); ?>
</div>
<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>
<?php
$trans = array();
foreach($model->verseTranslations as $p)
{
$trans[$p->id] = $p->translation_text;
}
?>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I have an array in my _form.php file.
<?php
$trans = array();
foreach($model->verseTranslations as $p)
{
$trans[$p->id] = $p->translation_text;
}
?>
if i write print_r($trans); Its output like this.
Array ( [3] => In the name of ALLAH, most Gracious, most Compassionate. [4] => شروع الله کا نام لے کر جو بڑا مہربان نہایت رحم والا ہے [5] => En el nombre de Alá, el Compasivo, el Misericordioso )
Now I want to assign this variable i.e. $trans to $model in _form.php file of yii framework, so that i easily access it on controller and then easily submit it to the separate table.
I also want to use it in textArea.
Hope you understand my question.
Any help will be appreciated.
Thanks.
instead of performing this task in view file , you should do it in the controller like
public function actionCreate()
{
$model=new MODELNAME;
// your rest of code
$trans = array();
foreach($model->verseTranslations as $p)
{
$trans[$p->id] = $p->translation_text;
}
// and then you can send this variable to the view by rendering the view file
$this->render('create',array('model'=>$model,'trans'=>$trans));
}
You can not send an array from view to controller, but there is a way (No Professional Way) to send:
put it in a session in your view (_form):
<?php $_SESSION["t"]=$trans;?>
and catch it in controller and then destroy session.
$trans=$_SESSION["t"];
it is better to do such operations in controller itself, instead of doing it in view and pass it to controller!
Add new property on your model like this.
class YOUR_MODEL_WITH_TRANS extends ParentModel
{
public $trans;
---
}
Go to your view file and assign it easily like this.
$model->trans=$trans;

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.

Getting error in Yii Multimodel Form

I am a newbie to the Yii framework.I want a multimodel form so I just went through this link and made all things like this.I have two table, first is group and another is member.
Group
ID
name
Member
id
group_id
firstname
lastname
Now I have made models for both tables and CRUD as well.I made change to GroupController file like this
public function actionCreate()
{
$group = new Group;
$member = new Member;
if(isset($_POST['Group'],$_POST['Member'])) {
//Populate input data to $group and $member
$group->attributes = $_POST['Group'];
$member->attributes = $_POST['Member'];
//Validate both $group and $member
$validate = $group->validate();
$validate = $member->validate() && $valid;
if($valid){
$group->save(false);
$member->save(false);
}
}
$this->render('create',array(
'group'=> '$group',
'member'=> '$member',
));
$model=new Group;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Group']))
{
$model->attributes=$_POST['Group'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
and after changing the group >> View >> create.php file like this
<?php echo $this->renderPartial('_form', array('group'=>$group, 'member'=>$member)); ?>
The _form file is like this
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'group-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($group,$member); ?>
<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($member,'firstname'); ?>
<?php echo $form->textField($member,'firstname',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($member,'firstname'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
but after all I am getting error like this Undefined variable: group .
So can some one please tell me how to solve this issue. I have lost one day behind this.So any help and suggestions will be highly appreciable.
You are doing multiple mistakes here ->
when you call
$this->render('create',array(
'model'=>$model,
));
you are not passing $group or $member models which you created in the group create controller. Change it to -
$this->render('create',array(
'group'=>$group,
'member'=>$member,
));
and secondly, there is no variable named $valid... change this part
$validate = $member->validate() && $valid;
if($valid){
to
$validate = $member->validate() && $validate;
if($validate){
now things should work fine

Categories