Yii model rules "Failed to set unsafe attribute" - php

I've looking but can't get It to work.
These are my rules in model Acta.php
public function rules()
{
return array(
array('dominio', 'required'),
array('numero, velocidad, grupo, dni, cuit, plan_pago_id', 'numerical', 'integerOnly'=>true),
array('foto, observaciones, situacion, infractor, dominio, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, usuario', 'length', 'max'=>255),
array('hora', 'length', 'max'=>11),
//Here is the problem with only this three attributes
array('municipio, cinemometro, fecha_labrada', 'safe', 'on'=> 'create,update'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, numero, fecha_labrada, velocidad, grupo, foto, observaciones, situacion, infractor, dominio, dni, cuit, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, hora, usuario, plan_pago_id', 'safe', 'on'=>'search'),
);
}
And this is the code on controller ActaController.php
public function actionCreate()
{
$model = new Acta;
if(isset($_POST['Acta']))
{
...
code setting data on $_POST['Acta']
...
$model->attributes = $_POST['Acta'];
$model->save();
}
$this->redirect(array('ingresar'));
}
I can't see the problem. Should be working right?
EDIT:
I thought that the scenario was set automatically. I was wrong.
To fix this the scenario must be set before the attributes:
...
$model->setScenario('create');
$model->attributes = $_POST['Acta'];
...

Before you save, You absolutely have some errors. To be aware about errors do like below:
if($model->validate()){
//NO ERRORS, SO WE PERFORM SAVE PROCESS
$model->save()
}else{
//TO SEE WHAT ERROR YOU HAVE
CVarDumper::dump($model->getErrors(),56789,true);
Yii::app()->end();
//an alternative way is to show attribute errors in view
}
On the other hand, it seems you set some attributes as safe on specific scenarios. But you did not set the scenario.
to set scenario, do like below:
$model->setScenario('THE SCENARIO NAME');
Or:
$model=new YOURMODELNAME('SCENARIO NAME');
I hope it help

Related

Yii 1.x - required field saves empty

I have a field set as required in the model, yet I have seen users saving it as an empty string (ie. ''). When I tested it, I do receive the "Cannot be blank" message properly, so don't know how to prevent this in the future. Do I have to specify all scenarios in the rule (eg, 'insert', 'update')? By the way, I tried updating the field, and it doesn't let me save it empty (I even tries spaces).
These are the rules applied on the field (model):
public function rules()
{
return array(
array('field', 'required'),
array('field', 'length', 'max'=>4096),
array('field', 'safe', 'on'=>'search'),
);
}
For #RiggsFolly :) the controller action:
public function actionUpdate($id)
{
$model = Model::model()->findByPk($id);
$formData = Yii::app()->request->getPost('Model');
if ($formData)
{
$model->attributes = $formData;
$model->save();
}
$this->render('update',array(
'model'=>$model
));
}
... and the view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form'
)); ?>
<?php echo $form->textArea($model,'text',array( 'rows'=>5 ')); ?>
<?php $this->endWidget(); ?>
Can you imagine any scenario this field could be saving an empty string in the database?

upload file in Yii not showing image name/path

im here again with a new problem. I am trying to upload a file using yii upload function.
Everything saves well, exept for the image. Here's my code:
Controller:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$dir = Yii::getPathOfAlias('webroot.images.producten');
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Producten']))
{
$model->attributes=$_POST['Producten'];
$model->images=CUploadedFile::getInstance($model,'images');
$nf = $model->images;
if($model->save()){
$this->redirect(array('view','id'=>$model->id));
$model->images->saveAs($dir.'/'.$nf);
$model->images = $nf;
$model->save();
}
}
$this->render('update',array(
'model'=>$model,
));
}
Form:
<div class="row">
<?php echo $form->labelEx($model,'images'); ?>
<?php echo CHtml::activeFileField($model,'images'); ?>
<?php echo $form->error($model,'images'); ?>
</div>
Model:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('naam, beschrijving, prijs', 'required'),
array('images,', 'file', 'allowEmpty'=>true,
'safe' => true,
'types'=> 'jpg, jpeg, png, gif',
'maxSize' => (1024 * 300), // 300 Kb
),
array('aangepast_door', 'numerical', 'integerOnly'=>true),
array('naam', 'length', 'max'=>50),
array('prijs, actieprijs', 'length', 'max'=>10),
//array('toegevoegd, aangepast', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('naam, beschrijving, prijs, actieprijs', 'safe', 'on'=>'search'),
);
}
Please help me get this to work.
First of all add enctype= "multipart/form-data" to your form tag or add "enctype" option to associative array if you used form widget yo begin form.
If it will not helps you, please post var_dump($_POST) results here

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 compare date and time in model

I have model with rules
public function rules() {
return array(
array('user_id, name, start_date, timezones, start_hours, return_date, return_hours, location_start, location_end, trip_activity, trip_mean, status', 'required'),
array('user_id, return_hours, sign_off, saved, advise, time_notification, status', 'numerical', 'integerOnly'=>true),
array('name, going_with, start_hours, location_start, location_end, location_return, trip_activity, trip_mean', 'length', 'max'=>255),
array('created, modified, advise, notify_best_friend, notify_now, notify_returning, send_notification, sign_off', 'safe'),
array('going_with, location_return, time_notification, created, modified', 'default', 'setOnEmpty' => true, 'value' => null),
array('id, user_id, name, going_with, start_date, start_hours, return_date, return_hours, location_start, location_end, location_return, trip_activity, trip_mean, saved, advise, time_notification, status, created, modified', 'safe', 'on'=>'search'),
array(
'return_date',
'compare',
'compareAttribute'=>'start_date',
'operator'=>'>=',
'allowEmpty'=>false ,
'message'=>'{attribute} must be greater than "{compareValue}".'
),
array(
'return_hours',
'compare',
'compareAttribute'=>'start_hours',
'operator'=>'>',
'allowEmpty'=>false ,
'message'=>'{attribute} must be greater than "{compareValue}".'
),
);
}
I want to compare date and time...
In case: 'return_date' >= 'start_date'... it's ok.
In case 'return_date' == 'start_date', so 'return_hours > 'start_hours' but with rules above I can't compare them.
What's solution? thanks!
You can achieve this using a custom validator.
public function comparedates($attribute,$params)
{
$message=Yii::t('yii','{attribute} must be greater than "{compareValue}".');
if(CDateTimeParser::parse($this->return_date, "yyyy-MM-dd") < CDateTimeParser::parse($this->start_date, "yyyy-MM-dd"))
{
$params=array('{attribute}'=>$this->getAttributeLabel('return_date'),'{compareValue}'=>$this->getAttributeLabel('start_date'));
$this->addError($attribute,strtr($message,$params));
}
else if(CDateTimeParser::parse($this->return_date, "yyyy-MM-dd") === CDateTimeParser::parse($this->start_date, "yyyy-MM-dd"))
{
if(CDateTimeParser::parse($this->return_hours, "hh") < CDateTimeParser::parse($this->start_hours, "hh")//change hh according to the format of return_hours and start_hours
{
$params=array('{attribute}'=>$this->getAttributeLabel('return_hours'),'{compareValue}'=>$this->getAttributeLabel('start_hours'));
$this->addError('return_hours',strtr($message,$params));
}
}
}
And in your rules
public function rules() {
return array(
//your previous rules
array('return_date','comparedates'),
);
}
Remember change the the patternparameter of CDateTimeParser::parse() from hh according to the format of your return_hours and start_hours

Categories