Im having this weird problem that causes my model to double insert into the database when ajaxvalidation is on for my form. I dont understand why this happens, but this keeps on conflicting with my custom validation and I cannot move on. Can someone enlighten me on the problem.
Model:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('category, ppmp_id', 'numerical', 'integerOnly'=>true),
array('category','required'),
array('q1, q2, q3, q4', 'numerical'),
array('category', 'myTestUniqueMethod'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('item_id, category, q1, q2, q3, q4, ppmp_id', 'safe', 'on'=>'search'),
);
}
public function myTestUniqueMethod($attribute,$params)
{
$sql = 'SELECT *
FROM ppmp_item
WHERE ppmp_id='.$this->ppmp_id.'and category='.$this->category;
$unique = Yii::app()->db->createCommand($sql)->queryRow();
if ($unique)
{
$this->addError('category', "Category already added to PPMP");
}
}
View:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'ppmp-item-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php
$data=PhilgepsCategory::model()->findAll();
$data=CHtml::listData($data,'id','class_name');
echo $form->dropDownList($model,'category',$data,array('options' => array('1'=>array('selected'=>true))));
?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q1'); ?>
<?php echo $form->textField($model,'q1'); ?>
<?php echo $form->error($model,'q1'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q2'); ?>
<?php echo $form->textField($model,'q2'); ?>
<?php echo $form->error($model,'q2'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q3'); ?>
<?php echo $form->textField($model,'q3'); ?>
<?php echo $form->error($model,'q3'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'q4'); ?>
<?php echo $form->textField($model,'q4'); ?>
<?php echo $form->error($model,'q4'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
Controller:
public function actionCreate($ppmp,$bal)
{
$model=new PpmpItem;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PpmpItem']))
{
$model->attributes=$_POST['PpmpItem'];
$model->ppmp_id = $ppmp;
$valid=$model->validate();
if($valid)
if($model->save())
$this->redirect(array('ppmp/view','id'=>$ppmp));
}
$this->render('create',array(
'model'=>$model,
'ppmp'=>$ppmp,
'bal'=>$bal,
));
}
The problem is that you shouldn't execute save() method when validating, because it will save when doing the ajax validation and when sending the data trough the form, so, you should do something like this:
...
...
if(isset($_POST['ajax']) && $_POST['ajax']==='ppmp-item-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$valid=$model->validate();
if($valid)
if($model->save())
...
...
This is the same that gii uses to validate using ajax.
Related
I am able to send simple email to receiver.Now i have to be able to select a email format from existing different formats and this template must appear in my message box.i should also be able to change the content of the template that appears in message box before sending to receiver.How to do this?
My code for view form
<div class="form wide">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'mail-form',
'enableAjaxValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'), // ADD THIS
)); ?>
<div class="row col2">
<?php echo $form->labelEx($model,'email_from'); ?>
<?php echo $form->textField($model,'email_from',array('size'=>50,'maxlength'=>50,'readonly'=>'readonly')); ?>
<?php echo $form->error($model,'email_from'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'email_to'); ?>
<?php echo $form->textField($model,'email_to',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'email_to'); ?>
</div>
<div style="clear:both"></div>
<div class="row col2">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>250)); ?>
<?php echo $form->error($model,'subject'); ?>
</div>
<div style="clear:both"></div>
<div class="row col2">
<?php echo $form->labelEx($model,'message'); ?>
<?php echo $form->textArea($model,'message',array('style'=>'width: 680px; height: 300px;')); ?>
<?php echo $form->error($model,'message'); ?>
</div>
<div style="clear:both"></div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord ? 'Send' : 'Send',array('class' => 'btn'));
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Try below code:
public function actionContact() {
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$status = Yii::$app->mailer->compose()
->setTo($model->email_to)
->setFrom([$model->email_from => $model->email_from])
->setSubject($model->subject)
->setTextBody($model->message)
->send();
if ($status) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
You can also create a email_template directory under views folder and create template file in which you can set email template content.
you can use js or ajax to do the same.
1: Use jQuery:
I assume that you are using jQuery. So use ajax.
.......JS Cod........
/*I assume that you have your template data in an attribute like data-template-data=""*/
$('#select_template_id').chang(function(){
template=$(this).attr('data-template-data');
$('#template_edit_box').val(template);
});
I've went through this tutorial http://www.yiiframework.com/wiki/561/ajax-login-form-with-validation-errors-inside-jquery-modal-dialog/ It appears to be functioning properly, but instead of the form being in the modal dialog, it just renders it right on the page like zii.widgets.jui.CJuiDialog isn't even there.
<?php $this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'login-dialog',
'options'=>array(
'title'=>'Login',
'autoOpen'=>false,
),
));?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user_login_form',
'enableAjaxValidation'=>false,
'enableClientValidation'=>true,
'method' => 'POST',
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
)); ?>
<h1>
Login</h1>
<p>
Please fill out the following form with your login credentials:</p>
<p class="note">
Fields with <span class="required">*</span> are required.</p>
<div id="login-error-div" class="errorMessage" style="display: none;">
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array("onfocus"=>"$('#login-error- div').hide();")); ?>
<?php //echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array("onfocus"=>"$('#login-error- div').hide();")); ?>
<?php //echo $form->error($model,'password'); ?>
<p class="hint">
Hint: You may login with <tt>demo/demo</tt>.
</p>
</div>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
<div class="row submit">
<?php echo CHtml::ajaxSubmitButton(
'Sign In',
array('/site/login.GetLogin'),
array(
'beforeSend' => 'function(){
$("#login").attr("disabled",true);
}',
'complete' => 'function(){
$("#user_login_form").each(function(){ this.reset();});
$("#login").attr("disabled",false);
}',
'success'=>'function(data){
var obj = jQuery.parseJSON(data);
// View login errors!
// alert(data);
if(obj.login == "success"){
$("#user_login_form").html("<h4>
Login Successful! Please Wait...</h4>
");
parent.location.href = "/";
}
else{
$("#login-error-div").show();
$("#login-error-div").html("Login failed! Try again.");$("#login-error-div").append("
");
}
}'
),
array("id"=>"login","class" => "btn btn-primary")
); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
<?php $this->endWidget('zii.widgets.jui.CJuiDialog'); ?>
Its suppose to render like this above so when i click the link below it opens
echo CHtml::link('Login', array('/site/login.GetLogin'), array('onclick'=>'$("#login-dialog").dialog("open"); return false;'));
Its built in a widget, if you have a look at the tutorial. Here's the complete widget
<?php
class loginProvider extends CWidget{
public static function actions(){
return array(
'GetLogin'=>'application.components.actions.getLogin',
);
}
public function run(){
$this->renderContent();
}
protected function renderContent(){
echo '<span style="float:right;">';
if(Yii::app()->user->isGuest){
echo CHtml::link('Login', array('/site/login.GetLogin'), array('onclick'=>'$("#login-dialog").dialog("open"); return false;'));
echo '</span>';
$this->getController()- >renderPartial('application.components.views.login',array('model'=>new LoginForm));
}
else
echo CHtml::link('Logout ('.Yii::app()->user->name.')', array('site/logout'), array('visible'=>!Yii::app()->user->isGuest));
echo '</span>';
}
}
I'm new to Yii framework and I need to display the validation error message as in login form "Username cannot be blank". Now, I have a text field where I updated the fields and the during validation I want a message to be displayed. How can I do this?
Controller
public function actionUpdate($id)
{
$model = $this->loadModel($id);
// set the parameters for the bizRule
$params = array('GroupzSupport'=>$model);
// now check the bizrule for this user
if (!Yii::app()->user->checkAccess('updateSelf', $params) &&
!Yii::app()->user->checkAccess('admin'))
{
throw new CHttpException(403, 'You are not authorized to perform this action');
}
else
{
if(isset($_POST['GroupzSupport']))
{
$password_current=$_POST['GroupzSupport']['password_current'];
$pass=$model->validatePassword($password_current);
$model->attributes=$_POST['GroupzSupport'];
if($pass==1)
{
$model->password = $model->hashPassword($_POST['GroupzSupport']['password_new']);
if($model->save())
$this->redirect(array('/messageTemplate/admin'));
}
else {$errors="Incorrect Current password"; print '<span style="color:red"><b>';
print '</b><b>'.$errors;
print '</b></span>';}
}
$this->render('update',array(
'model'=>$model,
));
}
}
View
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'password-recovery-reset-password-form',
'enableAjaxValidation'=>false,
)); ?>
<div class="row"><?php
echo $form->labelEx($model,'username');
echo $form->textField($model,'username',array('size'=>45,'maxlength'=>150));
echo $form->error($model,'username');
?></div>
<div class="row">
<?php echo $form->labelEx($model,'current password'); ?>
<?php echo $form->passwordField($model,'password_current',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_current'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'new password'); ?>
<?php echo $form->textField($model,'password_new',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_new'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'confirm new password'); ?>
<?php echo $form->passwordField($model,'password_repeat',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'password_repeat'); ?>
</div>
<div class="row buttons"><?php
echo CHtml::submitButton('Reset Your Password');
?></div><?php
$this->endWidget(); ?>
</div>
Now currently I'm displaying it at the top.
I want to display it right on the textfield as in login page. How can I do this?
Before redirect, add the message to the desired field.
In the model Validator:
$this->addError('field_name', "Message error.");
Or in Controller action:
$model->addError('field_name', "Message error.");
I have created two models :User and UserProfile , Now I want display in some fields of UserProfile in User view (_form) , on create action in user table I have done this :
public function actionCreate() {
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$user_form= new TblUser;
$profile_form = new TblUserProfile;
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];
$profile_form->attributes=$_POST['profile_form'];
// validate BOTH $a and $b
$valid=$user_form->validate();
$valid=$profile_form->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$user_form->save(false);
$profile_form->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'user_form'=>$user_form,
'profile_form'=>$profile_form,
));
}
Then ,
This is my _form class of user table
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo Chtml::errorSummary($user_form,$profile_form); ?>
<div class="row">
<?php //echo $form->labelEx($model,'id'); ?>
<?php echo $form->hiddenField($user_form,'id'); ?>
<?php //echo $form->error($model,'id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user_form,'password'); ?>
<?php echo $form->passwordField($user_form,'password',array('size'=>40,'maxlength'=>40)); ?>
<?php echo $form->error($user_form,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user_form,'username'); ?>
<?php echo $form->textField($user_form,'username',array('size'=>45,'maxlength'=>45)); ?>
<?php // echo $form->error($user_form,'username'); ?>
</div>
<div class="row">
<?php //echo $form->labelEx($model,'Is_active'); ?>
<?php echo $form->HiddenField($user_form,'Is_active'); ?>
<?php //echo $form->error($model,'Is_active'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($profile_form,'user_first_name '); ?>
<?php echo $form->textField($profile_form,'user_first_name ',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($profile_form,'user_first_name '); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user_form->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php echo CHtml::endForm(); ?>
<!-- form -->
Now , I have render both models in same view like this ,
<?php echo $this->renderPartial('_form',
array('user_form'=>$user_form,'profile_form'=>$profile_form)); ?>
Problem which I am facing after doing all this is :
Undefined variable: form
C:\wamp\www\topicoll\protected\views\tblUser\_form.php(9)
01
02
03 <?php echo CHtml::beginForm(); ?>
04
05
06
07 <p class="note">Fields with <span class="required">*</span> are required.</p>
08
09 <?php echo CHtml::errorSummary($user_form,$profile_form); ?>
10
11 <div class="row">
12 <?php //echo $form->labelEx($model,'id'); ?>
13 <?php echo $form->hiddenField($user_form,'id'); ?>
14 <?php //echo $form->error($model,'id'); ?>
15 </div>
16
17 <div class="row">
18 <?php echo $form->labelEx($user_form,'password'); ?>
19 <?php echo $form->passwordField($user_form,'password',array('size'=>40,'maxlength'=>40)); ?>
20 <?php echo $form->error($user_form,'password'); ?>
21 </div>
Please tell me what I am missing !
oh.. you are using CHtml to start a form CHtml::beginForm() and to end CHtml::endForm()
if you do so, you have to use CHtml to generate form elements as well i.e. CHtml::activeTextfield($model, 'field', array()) and CHtml::activeLabelEx($model, 'field') in all all places in your _form
other way is...
add this code instead of CHtml::beginForm().
$form=$this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>false,
'clientOptions'=>array(
),
));
and add this code in place of CHtml::endForm()
$this->endWidget();
it will fix your problem.
In your _form.php replace <?php echo CHtml::beginForm(); ?> with
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-form',
'type'=>'horizontal',
'enableAjaxValidation'=>false,
)); ?>
and <?php echo CHtml::endForm(); ?> with
<?php $this->endWidget(); ?>
And in your controller change the code block
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];
$profile_form->attributes=$_POST['profile_form'];
with
if(isset($_POST['TblUserProfile'], $_POST['TblUser'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['TblUser'];
$profile_form->attributes=$_POST['TblUserProfile'];
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'profile-form',
'type'=>'horizontal',
'enableAjaxValidation'=>false,
)); ?>
and <?php echo CHtml::endForm(); ?> with
<?php $this->endWidget(); ?>
And in your controller change the code block
if(isset($_POST['user_form'], $_POST['profile_form'])){
// populate input data to $a and $b
$user_form->attributes=$_POST['user_form'];`enter code here`
$profile_form->attributes=$_POST['profile_form'];
with
// Post model
return array(
'categories' => array(self::MANY_MANY, 'Category', 'categories_posts(post_id, category_id)')
);
I already have the setup of tables
posts
id, title, content
categories
id, name
categories_posts
post_id, category_i
The problem I have is that I am getting an error when creating this form:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-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,'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,'uri'); ?>
<?php echo $form->textField($model,'uri',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'uri'); ?>
</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>
<div class="row">
<?php // echo $form->labelEx($model,'content'); ?>
<?php echo CHtml::activeDropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>
<?php // echo $form->error($model,'content'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
The error is:
Property "Post.category_id" is not defined.
I am quite confused. What should I be doing to correct this?
I use the CAdvancedArBehavior to make this easier. I wouldn't be surprised if something like this gets rolled into the Yii core eventually either:
http://www.yiiframework.com/extension/cadvancedarbehavior/
It lets you write code like this in your controller:
$model->categories = $_POST['Post']['categories'];
I use this with the more-bugggy-than-I-would-like "Relation" widget/extension. You might need to use that to get the POST variables to structure correctly, I'm not sure.
I honestly thought that Yii has something like Kohana or Cake in their AR anyway. I guess I have to manually add them.
foreach ($_POST['category_id'] as $category_id)
{
$categoryPost = new CategoryPost;
$categoryPost->category_id = $category_id;
$categoryPost->post_id = $model->id;
$categoryPost->save();
}
Use in this way:
In controller
create object for category: $modelCat= new Category;
then in
<?php echo CHtml::activeDropDownList(**$modelCat**,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>