Here i am using fileField in CActiveForm but in model the validation rules are not working for that field here is my code
model code
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('image', 'required'),
//array('imageId, userId, courseId, departmentId, createdOn, lastModifiedOn, lastModifiedBy', 'required'),
array('image', 'file', 'types' => 'jpg, txt, pdf, gif, png', 'allowEmpty'=>'false'),
array('courseId, departmentId', 'numerical', 'integerOnly'=>true),
array('lastModifiedBy', 'length', 'max'=>45),
array('createdOn, lastModifiedOn', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, image, imageId, userId, courseId, departmentId, createdOn, lastModifiedOn, lastModifiedBy', 'safe', 'on'=>'search'),
);
}
view code
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'uploadinfo-form',
'enableAjaxValidation'=>false,
'enableClientValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<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,'image'); ?>
<?php echo $form->fileField($model,'image'); ?>
<?php echo $form->error($model,'image'); ?>
</div>
controller code
public function actionCreate()
{
$model=new Uploadinfo;
if(isset($_POST['Uploadinfo']))
{
$model->attributes=$_POST['Uploadinfo'];
print_r($_POST['Uploadinfo']);
$file=CUploadedFile::getInstance($model,'image');
print_r($file->getName());
die();
if($model->save())
{
$model->image->saveAs('path/to/localFile');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
here the required and file validation rule are not working
Try this for your controller code :
public function actionCreate()
{
$model=new Uploadinfo;
if(isset($_POST['Uploadinfo']))
{
$model->attributes=$_POST['Uploadinfo'];
$file=CUploadedFile::getInstance($model,'image');
if($model->validate() && $model->save())
{
$model->image->saveAs('path/to/localFile');
}
}
$this->render('create', array('model'=>$model));
}
You should set allow_empty=>true for it to work watch this post link:
array('image', 'file', 'types' => 'jpg, txt, pdf, gif, png', 'allowEmpty'=>true,'on'=>'update', 'on'=>'insert'),
and in your view
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'uploadinfo-form',
'enableAjaxValidation'=>true,
'enableClientValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
Related
my problem is with two or more files.
this codes is form Yii application development cookbook(2nd edition), chapter 4
i use Yii 1.1.14
controller:
<?php
class UploadController extends Controller
{
function actionIndex()
{
$dir = Yii::getPathOfAlias('application.uploads');
$uploaded = false;
$model=new Upload();
if(isset($_POST['Upload']))
{
$model->attributes=$_POST['Upload'];
$files=CUploadedFile::getInstances($model,'file');
if($model->validate()){
foreach($files as $file)
$file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'dir' => $dir,
));
}
}
model:
<?php
class Upload extends CFormModel
{
public $file;
public function rules()
{
return [
['file', 'file', 'types'=>'jpg'],
];
}
}
view:
<?php if($uploaded):?>
<p>File was uploaded. Check <?php echo $dir?>.</p>
<?php endif ?>
<?php echo CHtml::beginForm('','post',array('enctype'=>'multipart/form- data'))?>
<?php echo CHtml::error($model, 'file')?>
<?php echo CHtml::activeFileField($model, "[0]file")?>
<?php echo CHtml::activeFileField($model, "[1]file")?>
<?php echo CHtml::submitButton('Upload')?>
<?php echo CHtml::endForm()?>
help me, please
You should fix form enctype, use multipart/form-data instead of multipart/form- data.
You could use CMultiFileUpload
controller:
$images = CUploadedFile::getInstancesByName('image');
foreach ($images as $image => $pic) {
}
view:
$this->widget('CMultiFileUpload', array(
'name' => 'image',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
));
Add to model 'maxFiles' param, if you need validation to work properly for multifiles upload.
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,gif,png', 'maxSize'=>'204800', 'allowEmpty'=>true, 'maxFiles'=>4),
);
}
No Model Validations are happening On Update. $model->validate() returns true always. So save happens even if wrong data
Following is change password functionality
View
<?php echo $form->passwordField($model, 'currentpassword', array('class'=>'form-control','required'=>'required', 'value'=>'', 'maxlength'=>'40', 'pattern'=>'[a-zA-Z0-9-]{6,40}', 'title'=>'Password should be 6-40 characters containing a-z and 0-9')); ?>
<?php echo $form->error($model, 'currentpassword'); ?>
<?php echo $form->passwordField($model, 'password', array('class'=>'form-control','required'=>'required', 'value'=>'', 'maxlength'=>'40', 'pattern'=>'[a-zA-Z0-9-]{6,40}', 'title'=>'Password should be 6-40 characters containing a-z and 0-9')); ?>
<?php echo $form->error($model, 'password'); ?>
<?php echo $form->passwordField($model, 'confirmpassword', array('class'=>'form-control','required'=>'required', 'value'=>'', 'maxlength'=>'40', 'pattern'=>'[a-zA-Z0-9-]{6,40}', 'title'=>'Password should be 6-40 characters containing a-z and 0-9')); ?>
<?php echo $form->error($model, 'confirmpassword'); ?>
Controller
public function actionChangepassword()
{
$this->layout = (Yii::app()->request->isAjaxRequest) ? '//layouts/ajax' : '//layouts/precolumn2';
$model = new User('changepassword');
$data = array();
if (isset($_POST['User'])) {
$model = User::model()->findByPk(Yii::app()->User->getId());
$model->attributes=$_POST['User'];
if ($model->save()) {
$message = array(
'type' =>'success',
'message' =>'Password Changed.');
$data['message'] = $message;
}
}
$data['model'] = $model;
$this->render('changepassword',$data);
}
Model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, user_type_id', 'required','on'=>'signup'),
array('name, email', 'length', 'max'=>255),
array('email', 'required','on'=>array('recover','signup')),
array('email', 'exists','on'=> 'recover'),
array('email', 'unique'),
array('email', 'email'),
array('user_login_count, user_like_count, user_share_count, user_view_count, user_comment_count, user_rating_count', 'numerical', 'integerOnly'=>true),
array('password', 'length', 'max'=>100),
array('password, confirmpassword', 'required','on'=>array('signup','resetpassword','changepassword')),
array('confirmpassword', 'compare', 'compareAttribute'=>'password','on'=>array('signup','resetpassword','changepassword'),'message'=>'Passwords dont match'),
array('currentpassword', 'compareCurrentPassword','on'=>array('changepassword')),
);
}
Check out your line $model = User::model()->findByPk(Yii::app()->User->getId());
Looks like you need to set the scenario in there as you're creating a new user without the 'changepassword' scenario.
For example:
$model = User::model('changepassword')->findByPk(Yii::app()->User->getId());
Im trying to upload images and add to db file name and now Im stuck, because it wont add entry to db.
Error in debugger is Property "EeCarTypes.foto" is not defined.
controllers relavent code:
public function actionCreate()
{
$model=new EeCarTypes;
$path = Yii::app()->basePath . '/../images/upload/cartypes';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['EeCarTypes']))
{
$model->attributes=$_POST['EeCarTypes'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs( $path . '/adsfasdfadf' );
}
}
$this->render('create', array('model'=>$model));
}
view code:
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and model code:
public $image;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'ee_car_types';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array( 'image', 'file', 'types' => 'jpg, gif, png'),
array('car_type', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, car_type', 'safe', 'on'=>'search'),
);
}
I think anything else is irelevent here. Please help me :)
**Replace your view code**
echo $form->fileField($model, 'image');
with
<?php echo CHtml::activeFileField($model, 'image'); ?>
**In your controller file**
if(isset($_POST['EeCarTypes']))
{
$rnd = rand(0,9999);
$model->attributes=$_POST['EeCarTypes'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
$model->attributes=$_POST['EeCarTypes'];
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/upload/cartypes'.$fileName);
$this->redirect(array('index'));
}
}
At your model you should create a name property for the image and the field at the database. Then assign the file name to this property at your action method before you call the save(), like this:
$file = CUploadedFile::getInstance($model,'image');
$model->image_name = $file->name;
//use this if you want to save the file type but first create the image_type property
$model->image_type = $file->type;
[...]
Create an attribute with the name foto in your model EeCarTypes and look here
Im trying to add a captcha using yii to my contact form, but there is some problem with validation.
My model
class ContactForm extends CFormModel
{
public $verifyCode;
public function rules()
{
return array(
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'captchaRequired'),
array('verifyCode', 'safe'),
);
}
}
Code in my controller
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array( 'allow', //allow all users to perform advertise and index action
'actions' => array('advertise','index', 'captcha'),
'users' => array('*'),
),
);
}
public function actions() {
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
'testLimit'=> '2',
),
)
}
public actionAdvertise()
{ $model = new ContactForm;
$model->scenario = 'captchaRequired';
if($model->validate()){
//some code
} else {
$this->render('advertise', array('model' => $model));
}
}
}
Code in my advertise.php view
<form action="" method="post">
<?php
$form=$this->beginWidget('CActiveForm',array(
'id'=>'contact-form',
'enableAjaxValidation'=>false,
));
?>
<?php if(CCaptcha::checkRequirements()){ ?>
<div class="row">
<div class="contact_field_wrapper">
<?php echo '<b>ARE YOU HUMAN?</b><br />'.$form->labelEx($model, 'verifyCode'); ?>
<div class="captcha user-captcha">
<?php $this->widget('CCaptcha',array( 'captchaAction'=>'site/captcha' ));
?>
<?php echo $form->error($model, 'verifyCode'); ?>
<?php echo '<br />'.$form->textField($model,'verifyCode'); ?>
<div class="hint">Please enter the letters as they are shown in the image above.<br/>
Letters are not case-sensitive.
</div>
</div>
</div>
</div>
<?php } ?>
<?php $this->endWidget(); ?>
</form>
The problem is that $model->validate() returns false when correct code in inputted.
$model->getErrors() is always returning 'Verification code is incorrect'.
your model is empty , because you didn't pass any value to $model->attriburtes
Do this :
if($_POST['ContactForm'])
{
$model->attributes() = $_POST['ContactForm'];
if($model->validate())
{
//some code
}
}
$this->render('advertise', array('model' => $model));
How can i update, some field, forexample firstname or lastname or email without doing any change on password field
My model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, salt, password, firstname, lastname, email', 'required', 'on' ),
array('superuser, status', 'numerical', 'integerOnly'=>true),
array('username, password, salt', 'length', 'max'=>32),
array('firstname, lastname,image', 'length', 'max'=>80),
array('email', 'length', 'max'=>128),
array('id, username, password, salt, firstname, lastname, email, superuser, status', 'safe', 'on'=>'search'),
);
}
AND in model i have
public function beforeValidate()
{
$this->salt = '1294455567';
return parent::beforeValidate();
}
you can do like this also...
public function beforeSave()
{
if(!$this->getIsNewRecord())
unset($this->password);
return parent::beforeSave();
}
Hope it may help you..
You can use Yii scenarions. For example in your model you has next validation rules:
public function rules()
{
return array(
array('username, salt, password, firstname, lastname, email', 'required', 'on' => 'create'),
array('email, username, firstname, lastname', 'someValidationRuleOrMethod', 'on' => 'update'),
);
}
When you need to create new user, need to set validation scenario:
$model = new User('create');
//some code
$model->validate();
Or:
$model = new User();
$model->scenario = 'create';
//some code
$model->validate();
When you need update exists user - use update scenario instead create:
$model = User::model()->findByPk($someId);
$model->scenarion = 'update';
//some code
$model->validate();
Also, I found this receipt on Russian Yii blog.
UPD You can use static method to hash password, and can call it every where:
public static function hashPassword($password)
{
return CPasswordHelper::hashPassword($password);
}
Create a User model object for single user, then update by assigning new value for field:
...
$user = User::model()->find("`t`.`username` = :USER", array(':USER' => 'example.user'));
$user->firstname = 'New First Name';
$user->lastname = 'New Last Name';
$user->email = 'email#user.new';
# Now update User here
if($user->update()) {
echo 'Updated';
}
...
Hi all what i have done is here....
My controller ::
public function actionUpdate($id){
$model=$this->loadModel($id,'User');
$oldImage = $model->image;
// $old_password = $model->password;
$model->password = '';
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
//If image not uploaded then set old image
if(!$this->uploadImage($model)){
$model->image = $oldImage;
}
if($model->save()){
Yii::app()->user->setFlash('success', "Data Updated successfully"); // Flash Message
$this->redirect(array('admin','id'=>$model->user_id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
My Model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('first_name, last_name, password, email,repeat_password', 'required',"on"=>'create'),
array('first_name, last_name, email', 'required',"on"=>'update'),
array('first_name, last_name', 'length', 'max'=>100),
array('password', 'length', 'max'=>30,'min'=>6),
array('repeat_password', 'compare', 'compareAttribute' => 'password', 'message'=>'Confirm Password must be same as password'),
array('email', 'length', 'max'=>50),
array('email', 'unique'),
//array('image', 'file', 'types'=>'jpg, gif, png'),
array('image', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('user_id, first_name, last_name, email', 'safe', 'on'=>'search'),
);
}
public function beforeSave(){
if(!empty($this->password))
$this->password = md5($this->password);
else
unset($this->password);
return parent::beforeSave();
}
My View ::
<?php
// If user update profile or update data then don't show password
if( ((#Yii::app()->request->getParam('act')!=="profile") && empty($_GET["id"])) || #$_GET["act"]=='changepwd' )
{
?>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('maxlength'=>20,'minlength'=>6)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row"><!-- Confirm password -->
<?php echo $form->labelEx($model,'Confirm Password'); ?>
<?php echo $form->passwordField($model,'repeat_password',array('maxlength'=>20,'minlength'=>6)); ?>
<?php echo $form->error($model,'repeat_password'); ?>
</div>
<?php } ?>
public function actionUpdate($id) {
$model=$this->loadModel($id);
if(isset($_POST['User']))
{
$password = $model->password;
$model->attributes=$_POST['User'];
if($password === $model->password) {
$model->password = $password;
} else {
$model->password = md5(SALT . $model->password);
}
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}