Comapring rule between two variables in rules not working in Yii - php

I am doing a function to change the users password. Inside of the Users model I have create three variable like the following.
public $oldPassword;
public $newPassword;
public $repatePassword;
Now I need to compare newPassword and repare password together and i added the followinf rule inside of the model.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password', 'required'),
array('username', 'length', 'max'=>20),
array('password', 'length', 'max'=>255),
array('oldPassword', 'findPassword', 'on' => 'changePwd'),
//array('repatePassword','compare','compareAttribute'=>'newPassword', 'on'=>'changePwd'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, username, password', 'safe', 'on'=>'search'),
);
}
I have the following form.
<div class="row">
<?php echo $form->labelEx($model,'Old Password'); ?>
<?php echo $form->passwordField($model,'oldPassword',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'oldPassword'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'New Password'); ?>
<?php echo $form->passwordField($model,'newPassword',array('maxlength'=>255)); ?>
<?php echo $form->error($model,'newPassword'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Repate Password'); ?>
<?php echo $form->passwordField($model,'repatePassword',array('maxlength'=>255)); ?>
<?php echo $form->error($model,'repatePassword'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Update'); ?>
</div>
Now when I exactly put the exc same values in both of the fields it still gives me that the values are not the same. Why is this?

Add the following rule to your rules() method.
array('oldPassword,newPassword,repatePassword','required','on'=>'changePwd')
Without a rule for an attribute, that attribute will NOT be massively assigned to the model and so will not be available for any validation.
Alternately, you can change required to be safe if you just want to allow assignment, and not make the attributes actually required, although in this case required makes sense to me.
Based on your rules, the reason it says they do not match is because newPassword is not being assigned, and so is an empty string being compared to your intended password.

Related

How to save input in yii to database

I have this code Im trying to save the content and the title from a form I made..It has an id that autoincrement the id number adds in the database but the title and the content isn't/cant be save in the database. Can you please check my code if I've done something wrong? or what I'm lacking at.
Here is my model ContentForm.php
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels()
{
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
// 'email' => 'Email',
// 'usrtype' => 'Usrtype',
);
}
Here is my view content.php
<div>
<p>User: <a href="viewuserpost">
<?php
echo Yii::app()->session['nameuser'];
?>
</a>
</p>
</div>
<h1>Content</h1>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Title:
<div class="row">
<?php
echo $form->textfield($model,'title');
?>
</div>
</br>
Body:
<div class="row">
<?php
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
?>
</div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save');
?>
</div>
<?php $this->endWidget(); ?>
and here is my content action in my sitecontroller.php
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
}
$this->render('content',array('model'=>$model));
}
Please help.
Remove
public $content;
public $title;
from your class.
Yii uses PHP magic methods. And when you add attributes to your class, PHP doesn't call them but references to your explicitly written attributes.
Moreover, you should add some validation, if you use $model->attributes=$_POST['ContentForm'];. Another variant is to use unsecure $model->setAttributes($_POST[ContentForm], false) where false tells Yii to set all attributes, not only that are considered safe.
Note, that attributes is not real Model attribute, this is virtual attribute accessed through magic methods.
Also, you don't need three redirects. This is HTTP redirect to other page. This time, you just should just specify route to model view action and its parameter that is id, for example. Like this $this->redirect(array('content/view','id'=>$model->contentid));.
Of course, simplest way for you is to create new model and controller with actions using Gii.
you may missed rules , add this in your model ContentForm.php
public function rules()
{
return array(
array('content,title', 'safe'),
);
}
For more about model validation
http://www.yiiframework.com/wiki/56/reference-model-rules-validation/

Form Validation error on Yii Framework?

I'm new on Yii, I have Try Crud and succes. now try to create validation but Still error.
here my script
Model:Buku.php
public function rules()
{
return array(
array('judul, penulis'),
array('judul', 'length','max'=>50),
array('penulis', 'length', 'max'=>50),
array('judul,penulis', 'on'=>'search'),
);
}
Controller: BukuController.php
public function actionCreate()
{
$model = new Buku;
if(isset($_POST['Buku']))
{
$model->judul =$_POST['Buku']['judul'];
$model->penulis =$_POST['Buku']['penulis'];
$model->save();
/*if($model->save())
{
Yii::app()->user->setFlash('Succes', "Data berhasil Disimpan");
$this->redirect(array('index'));
}*///end of
}//end if isset
$this->render('create',array('model'=>$model));
}//end of class
View: create.php
<div class="form">
<h2>Add Data</h2>
<?php echo CHtml::beginForm(array('buku/create'));?>
<?php
echo CHtml::errorSummary($model);
?>
<div class="row">
<?php echo CHtml::activeLabel($model,'judul');?>
<?php echo CHtml::activeTextField($model,'judul','');?>
<?php echo CHtml::errorSummary($model,'judul');?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'penulis');?>
<?php echo CHtml::activeTextField($model,'penulis','');?>
<?php echo CHtml::errorSummary($model,'penulis');?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit');?>
<?php echo CHtml::endForm();?>
</div>
</div>
the Error MEssage is
Buku has an invalid validation rule. The rule must specify attributes to be validated and the validator name
Anyone can Help This?
Im very appreciated Your answer.
Thanks
Pleas edit the first line, probably you wanted there 'required'
array('judul, penulis','required'),
And this is not needed:
$model->judul =$_POST['Buku']['judul'];
$model->penulis =$_POST['Buku']['penulis'];
instead you can use the mass-assignment: http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/
$model->attributes=$_POST['Buku'];
In Your Model class method rules first rule is invalid:
array('judul, penulis') -> no validation rule specified.
Try at least:
array('judul, penulis', 'required')
List of all Validation rules in Yii:
http://www.yiiframework.com/wiki/56/
How validation works
Parameters of a validator
Choice of validators
Scenarios
Validation rules reference
boolean : CBooleanValidator
captcha : CCaptchaValidator
compare : CCompareValidator
date : CDateValidator
default : CDefaultValueValidator
email : CEmailValidator
exist : CExistValidator
file : CFileValidator
filter : CFilterValidator
in : CRangeValidator
length : CStringValidator
numerical : CNumberValidator
match : CRegularExpressionValidator
required : CRequiredValidator
safe : CSafeValidator
type : CTypeValidator
unique : CUniqueValidator
unsafe : CUnsafeValidator
url : CUrlValidator
Selected readings
Built in validators in Yii....

Always fail to validate in Yii

I've been confused with validation rules in Yii. I am sure when I give inputs there is no mistakes, corresponds to the rules given.
This is the validation rules in my model:
// public $user_phone; //updated: this isn't necessary
public $maxId;
...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('user_phone', 'required', 'message'=>'{attribute} cannot be empty.<br />'),
array('user_phone', 'length', 'max'=>12),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('user_phone', 'safe', 'on'=>'search'),
);
}
This is when I call the validation function in the controller:
Updated: Added the assignment of the model's attributes
public function actionOrder(){
$order = new IptvOrder;
if(isset($_POST["IptvOrder"])) {
$order->attributes = $_POST["IptvOrder"]; // this is what I forgot
// some assignments to $id, $phone, $date, $time
if($order->validate()) {
$order->addOrder($id, $phone, $date, $time);
$this->redirect(array('order/orderConfirm'));
}
...blablabla...
}
And I put the validation error message in the view:
...blablabla...
<?php
echo $form->label($order,'Phone Number');
echo "<font color='red'> *</font>";
echo "<span style='font-size:10pt; color:#888888'><br/>Digunakan untuk konfirmasi pemesanan. Kerahasiaan kami jamin.</span><br/>";
echo $form->textField($order,'user_phone');
echo "<font color='red'>".$form->error($order, 'user_phone')."</font>";
?>
echo CHtml::submitButton('Pesan Sekarang', array('confirm' => 'Apakah anda yakin?
Silahkan cek pemesanan anda terlebih dahulu.'));
...blablabla...
// $form is CActiveForm, $order is the model
And it won't be redirected to order/orderConfirm although the textfield is not empty. Anybody can help? Thanks :)
Dump $order->attributes check the attribute user_phone has content or empty
Print out what your given error is from $order->getErrors()
About max length validation, because your input for that field is phone number, I exclude the possible of ASCII letter like below case
http://www.yiiframework.com/forum/index.php/topic/16338-validation-problem-with-length-on-textfields/
Updated: If your model name was Order as example, you should have to look like before you perform the validation
if(isset($_POST['Order']))
{
$order->attributes=$_POST['Order']; //<== Make sure you have set data for your order model before performing a validation
//validate part
...
}

Yii Captcha error

I am working in Yii and I am just a beginner and trying my best to learn the framework and here is where I am stuck at :
I have created a user model and the required forms that go with it, and I am trying to implement the Captcha for it :
This is my validation rules in the user model :
$public verifyCode
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, email', 'required'),
array('username','unique'),
array('email','email'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
array('username, password', 'length', 'max'=>45),
array('email', 'length', 'max'=>100),
array('active', 'length', 'max'=>1),
array('created_on, updated_on', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, username, password, email, created_on, updated_on, active', 'safe', 'on'=>'search'),
);
}
And this is my overriden action() in my userController :
public function actions(){
return array(
'captcha'=>array(
'class' => 'CCaptchaAction',
)
);
}
And this is my view file :
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
According to me, I think that I am doing everything correctly however, the captcha image is not getting generated. Oh and yes the GD library is installed and if I navigate to the site/contact, there the captcha is generated fine.
I dont seem to understand, where am i getting it wrong.
This is the thing that I see :
The forms seems to be working fine however, I cant see the the captcha image.
Any help would be appreciated.
Regards,
I got the answer, it is because of the access rules that are defined in the controller, I had to modify the controller accessControl like so :
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','captcha'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform every action
'actions'=>array('create','update','admin','delete'),
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}

Yii captcha picture Broken link

I just wondering how it is possible to copy exact code of Yii Framework demo-blog-contact , downloaded from Yii website to other yii application with same version library and it don't show captcha.
When i go to controller/action page ,it show broken link instead of captcha and when i open broken link image in new page it show another broken link.
I saw this link for common problem of CCaptcha and i checked gd library is up and running and i have function actions() with content of exact same as the link said and i don't define any access control filter in the application.
I saw this link and i don't have permission problem and this link and i don't ajax it.
I did exact same as this link said but no success. any help to show these captcha would be appreciated.
Controller :
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('create', 'captcha'),
'users'=>array('*'),
));
}
Model :
<?php
class ContactsM extends CFormModel {
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
View :
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->errorSummary($model); ?>
<?php if(extension_loaded('gd')): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row submit">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
As i understand from your comment You should Extend your Controller class from CController.
I want to share the fact i have understand :
My problem was :
I used inheritances and father class have some issue , the son class extend it but it do not show any error and i was thinking it works fine but in fact it didn't , i understand it till i used some of father function which in this case was CCaptcha.

Categories