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.
Related
I am developing this website that requires me to combine two models in one view where they have one to many relationship between them. The models name is Home and Image meaning Home has many Images but Image only has one Home.
I have manged to combine The view together but the problem that i encountering is to get all of the images. For example i have 6 images i want to display them or if i have 5 images i want to display them.
Home Controller UpdateMethod
public function actionUpdate($id)
{
$home=$this->loadModel($id);
$image=Image::model()->findByAttributes(array('homeId'=>$home->id));
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Home'],$_POST['Image'])){
$home->attributes=$_POST['Home'];
$image->attributes=$_POST['Image'];
$valid=$home->validate();
$valid=$image->validate() && $valid;
if($valid){
if($home->save()){
$image->save();
}
}
}
$this->render('update',array(
'home'=>$home,
'image'=>$image,
));
}
My _form.php to join them together
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'home-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($home); ?>
<div class="row">
<?php echo $form->labelEx($image,'imageUrl'); ?>
<?php echo $form->textField($image,'imageUrl',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($image,'imageUrl'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($home,'recentEvents'); ?>
<?php echo $form->textField($home,'recentEvents',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($home,'recentEvents'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($home,'introduction'); ?>
<?php echo $form->textArea($home,'introduction',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($home,'introduction'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($home->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Update I had FindByattribues instead of FindAllByAttribues in the model so now it is returning an array. Now how to process that array in the view?
Okay i figured it out by myself posting this to maybe help someone who needs it. I the view i did the following.
<?php
foreach($image as $image){
?>
<div class="row">
<?php echo $form->labelEx($image,'imageUrl'); ?>
<?php echo $form->textField($image,'imageUrl',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($image,'imageUrl'); ?>
</div>
<?php
}
?>
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)
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));
I know that usually you would just use the integrated CRUD delete button that is in admin however for my purposes I am requiring an actual page for delete that just has the id in a field and a submit button but so far it just produces the error view so any assistance is appreciated. I have tried to create it the same as my create and update pages are set up, please see the code below:
The link to the delete page:
<?php echo CHtml::link('Delete Article', array('delete', 'id'=>$pageid)); ?>
The link it produces:
http://local/..../Yii/news/index.php/delete?id=3
The controller:
public function actionDelete($id)
{
$model=$this->loadModel($id);
if(isset($_POST['news_model']))
{
$model->attributes=$_POST['news_model'];
if($model->save())
$this->redirect('index');
}
$this->render(array('delete', array(
'model'=>$model,
));
}
Delete.php:
<h2>Delete a news item</h2>
<?php echo $this->renderPartial('_form2', array('model'=>$model)); ?>
_form2.php
<?php echo $form->errorSummary($model); ?>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'news-model-form',
'enableAjaxValidation'=>false,
)); ?>
<div class="form">
<div class="row">
<?php echo $form->labelEx($model,'id'); ?><br>
<?php echo $form->textField($model,'id',array('size'=>50,'maxlength'=>128)); ?>
<?php echo $form->error($model,'id'); ?>
</div><br>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Delete a news item'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Thanks in advance for any help given.
You got an error in your php synax in _form2.php
<?php echo CHtml::submitButton($model->isNewRecord ? 'Delete a news item'); ?>
more like
<?php echo CHtml::submitButton($model->isNewRecord ? 'Delete a news item':'Delete an old item'); ?>
See the Ternary Operator in PHP: Comparison Operators
... yet I don't se the point in that sentence, to me it would seem a little bit more like:
<?php if (!$model->isNewRecord) echo CHtml::submitButton("Delete Record"); ?>
... but the record is guaranteed to not be new when it is loaded by $model=$this->loadModel($id);
Also, In Delete.php
<?php echo $this->renderPartial('_form2', array('model'=>$model)); ?>
would be more like
<?php echo $this->renderPartial('_form2', array('model'=>$model), true); ?>
or
<?php $this->renderPartial('_form2', array('model'=>$model)); ?>
Seel the documentation renderPartial(), specially pay attention to its return value its third argument. Turns out that you're actually echoing NULL. which explains why there is no display.
I would like to take the blog comment model and turn the form into a mulitimodel form but I have not been able to work this out. Would appreciate if anyone could point me in the right direction.
Taken the design below I want to add another table (OtherModel) off of comment with a FK in comment linking the tables.
Controller
public function actionView()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
));
}
protected function newComment($post)
{
$comment=new Comment;
$otherModel=new OtherModel;
if(isset($_POST['Comment'], $_POST['OtherModel']))
{
$comment->attributes=$_POST['Comment'];
$otherModel->attributes=$_POST['OtherModel'];
if($post->addComment($comment))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you...');
$this->refresh();
}
}
return $comment;
}
model
public function addComment($comment)
{
$comment->other_id=$otherModel->other_id;
$otherModel->save();
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
}
render form through CJuiTabs
'Comment'=>$this->renderPartial('/comment/_form',array($model->$comment=>),true)
form
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'author'); ?>
<?php echo $form->textField($model,'author',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,'author'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'content'); ?>
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'content'); ?>
</div>
// added otherModel as part of MMF
<div class="row">
<?php echo $form->labelEx($otherModel,'name'); ?>
<?php echo $form->textField($otherModel,'name',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($otherModel,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($otherModel,'description'); ?>
<?php echo $form->textArea($otherModel,'description',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($otherModel,'description'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Submit' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I think you have a mistake in your code given above: you are trying to use $otherModel variable instead of $comment rendered by your actionView() method.
Have you tried to use examples posted on yiiframework.com? I mean the link you've given in comment to your question. If it does not suit you, I afraid I've misunderstood your question.
I think you should validate both models before saving, otherwise you'd end up with a stale $otherModel record in your database.
protected function newComment($post)
{
$comment=new Comment;
$otherModel=new OtherModel;
if(isset($_POST['Comment'], $_POST['OtherModel']))
{
$comment->attributes=$_POST['Comment'];
$otherModel->attributes=$_POST['OtherModel'];
// also specify $otherModel as a param
if($post->addComment($comment, $otherModel))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you...');
$this->refresh();
}
}
return $comment;
}
public function addComment($comment, $otherModel)
{
// Validate both models, return false if there are errors.
// Errors should be available via $model->getErrors()
if ($comment->validate() && $otherModel->validate()) {
// save the otherModel first to obtain the generated ID
$otherModel->save();
$comment->other_id=$otherModel->id;
if(Yii::app()->params['commentNeedApproval'])
$comment->status=Comment::STATUS_PENDING;
else
$comment->status=Comment::STATUS_APPROVED;
$comment->post_id=$this->id;
return $comment->save();
} else {
return false;
}
}
Note: You may also use transactions here.