How to validate different model fields in one form in ?Yii - php

I have two models
1)TblRegistration : $model as object
-director
-experience
-language
2)TblLogin : $model2 as object
-email
-password
Both fields are included in TblRegistration/_form.php
By defaut TblRegistration fields validation is included in rules().
views/tblRegistration/_form.php
<div class="row">
<?php echo $form->labelEx($model,'director'); ?>
<?php echo $form->textField($model,'director',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'director'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'experience'); ?>
<?php echo $form->textField($model,'experience'); ?>
<?php echo $form->error($model,'experience'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'language'); ?>
<?php echo $form->textField($model,'language',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'language'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model1,'email'); ?>
<?php echo $form->textField($model1,'email'); ?>
<?php echo $form->error($model1,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model1,'password'); ?>
<?php echo $form->textField($model1,'password'); ?>
<?php echo $form->error($model1,'password'); ?>
</div>
models/TblRegistration.php
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('director, experience, language', 'required'),
array('experience', 'numerical', 'integerOnly'=>true),
array('director, language', 'length', 'max'=>50),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('reg_id, director, experience, language', 'safe', 'on'=>'search'),
);
}
I want to include TblLogin fields into model/TblRegistraion rules for validation.

You can manually validate a model by calling the validate() method:
if($modelA->validate() && $modelB->validate()) {
// Call save method, fix foreign keys, etc
$this->redirect(array('view'));
}
If there is an error the page will not be redirected so your form will reload. $form->error() will highlight the error fields. Also, when the first argument of errorSummary is an array containing your models, it will summarize them all for you.

Related

SQL injection of group_key in yii save?

I have an feedback form in yii which simply takes input and save in database. I know yii uses PDO for data save but still it is SQL vulnerable.
Controller
public function actionFeedback()
{
$model = new Feedback;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Feedback']))
{
$model->attributes = $_POST['Feedback'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('feedback',array(
'model'=>$model,'managerList'=>$managerList,'branchList'=>$branchList,
));
}
Model
public function rules()
{
return array(
array('branch, manager,comments', 'required'),
array('branch,manager', 'length', 'max'=>5),
array('comments', 'length', 'min'=>10, 'max'=>'2000'),
);
}
View
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'branch'); ?>
<?php echo $form->dropDownList($model,'branch', $branchList, array('prompt'=>'Select branch')); ?>
<?php echo $form->error($model,'branch'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'manager'); ?>
<?php echo $form->dropDownList($model,'manager', $managerList, array('prompt'=>'Select manager')); ?>
<?php echo $form->error($model,'manager'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comments'); ?>
<?php echo $form->extArea($model, 'comments', array('rows'=>15, 'cols'=>75)); ?>
<?php echo $form->error($model,'comments'); ?>
</div>
<?php $this->endWidget(); ?>
For me it is sql injection safe as in save the insert query is like
INSERT INTO feedback (branch,manager,comments) VALUES (:yp0,:yp1,:yp2). Bound with :yp0 = '2',:yp1='4',':yp2'='hello this is an testing comments'
Still on testing this by third party I saw they inserted a query in this so my system gives error like
duplicate entry for 4CuJhL8T2Oc1 for key 'group_key'
I searched it an found this error but unable to regenerate it from my front end anyone please suggest how it generated also please provide help to get prevent from this
Any help is appreciated

Geting multiple Records in update in Yii

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
}
?>

Setting default values and Creating into Database using Yii

I'm trying to create a new user but I'm having trouble trying to create the user because some of the values that are needed to create a user must be default values that I'm not quite sure how to set. I also need to input into a different table while the actual "create" happens from a different controller.
Here is my form code:
<?php
/* #var $this SystemUserController */
/* #var $model SystemUser */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'system-user-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,'party_id'); ?>
<?php echo $form->textField($model,'party_id',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'party_id'); ?>
</div>
!-->
<div class="row" id="toshow" style="display:none" name="suppliers"> <?php $supplier = SupplierHead::model()->findAll();
$list = CHtml::listData($supplier ,'head_id','head_name');
echo $form->DropDownList($model,'party_id',
$list, array('prompt'=>'Select Supplier')); ?>
</div>
<button id="abutton">Already a Supplier</button>
<script>
$(document).ready(function() {
$("#abutton").click(function(e){
e.preventDefault();
$("#toshow").css('display', 'block');
});
});
</script>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<script>
$("#supplier").click(function () {
$("#suppliers").show("slow");
});
</script>
<!--
<div class="row">
<?php echo $form->labelEx($model,'date_last_login'); ?>
<?php echo $form->textField($model,'date_last_login'); ?>
<?php echo $form->error($model,'date_last_login'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->textField($model,'status',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_created'); ?>
<?php echo $form->textField($model,'date_created'); ?>
<?php echo $form->error($model,'date_created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_modified'); ?>
<?php echo $form->textField($model,'date_modified'); ?>
<?php echo $form->error($model,'date_modified'); ?>
</div>
--!>
<div class="row">
<?php echo $form->labelEx($model,'user_role'); ?>
<?php echo $form->textField($model,'user_role',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'user_role'); ?>
</div>
<!--
<div class="row">
<?php echo $form->labelEx($model,'isLogin'); ?>
<?php echo $form->textField($model,'isLogin'); ?>
<?php echo $form->error($model,'isLogin'); ?>
</div>
--!>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
As you can see, I've commented out the attributes that I don't want to use. I also fixed the SystemUser model attributes rules() to define which attributes won't be needed for user input here:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('party_id, username, password', 'required'),
//array('isLogin', 'numerical', 'integerOnly'=>true),
array('party_id', 'length', 'max'=>20),
array('username', 'length', 'max'=>200),
array('password, user_role', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('party_id, username' 'on'=>'search'),
);
}
Finally, there's also a drop down list I included above from the form that is required to be inserted into a model of a different controller. How do I go about this?
The attributes that need default values are as follows:
date_last_login
status
date_created
date_modified
EDIT
I've uploaded a picture of what happens when I select "Create"
I decided not to add defaults try keeping them NULL just to see if the rules() would work. I
Any help?
Yii's model has methods such as:
beforeSave()
afterSave()
beforeValidate()
afterValidate()
and so on ...
which can be overridden into your model. If you want to set any default value before saving/validating you can use from mentioned methods in your model. Please take a look at the following example:
public function beforeSave() {
if (parent::beforeSave()) {
//Example
$this->date_modified=new New CDbExpression('NOW()');
//ANOTHER EXAMPLE
$this->date=date('Y-m-d',time());
// YOU CAN EVEN CALLING A WEBSERVICE
// ANYTHING THAT YOU WANT TO DO BEFORE SAVING INTO DATABASE
return true;
}
}
other methods such as afterSave and ... work like above.
I hope it help :)
You can use the rules for it like
public function rules()
{
return array(
// your other rules
array('myField','default','value'=>'my Name'),
// for date type use new CDbExpression('NOW()')
array('date_modified','default',
'value'=>new CDbExpression('NOW()'),
),
// rest of your rules
);
}
Try with this data type:
date_last_login : timestamp
status : enum('active','inactive')
date_created : timestamp
date_modified : timestamp
Defult Time stamp: current_timestamp

model validations not working when creating record in yii

I really don't know why is it happening my model validations are not working while creating record in yii.
doesn't display any errors .
The thing is if any of the required field is empty though it passes to the display page not displaying errors
but it doesn't insert the record as all required field a not filled.
My need is display errors in the same form i.e., validations should not pass if required fields are empty.
validation works with no issues in update, issues with create form
but it inserts the record if all required field are filled.
errors displayed in update are black not red as default by yii ...... is it due to the extension am using
model rules
array('name, category, model, brand, description, price', 'required'),
array('pimg', 'file','types'=>'jpg','on'=>'create'),
array('pimg', 'file','types'=>'jpg','on'=>'update', 'allowEmpty'=>true),
controller for create
$model=new controllername;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['controllername']))
{
$model->attributes=$_POST['controllername'];
$model->pimg=CUploadedFile::getInstance($model,'pimg');
$fileName = $model->pimg;
if($model->save())
$model->pimg->saveAs('images/'.$fileName);
$this->redirect(array('display','id'=>$model->productid));
}
$this->render('create',array(
'model'=>$model,
));
view
<?php $form=$this->beginWidget('CActiveForm',array(
'id'=>'form_name',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('size'=>60,'maxlength'=>60)); ?>
<?php echo $form->error($model,'name'); ?>
<?php echo $form->labelEx($model,'model'); ?>
<?php echo $form->textField($model,'model',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'model'); ?>
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>256)); ?>
<?php echo $form->error($model,'description'); ?>
<?php echo $form->labelEx($model,'pimg'); ?>
<?php echo $form->hiddenField($model,'pimg',array('length'=>222)); ?>
<?php echo $form->fileField($model, 'pimg',array('id'=>'imgInput',)); ?>
<?php echo $form->error($model,'pimg'); ?>
<?php echo $form->labelEx($model,'category'); ?>
<?php echo $form->dropDownList($model,'category',$model->getCat()); ?>
<?php echo $form->error($model,'category'); ?>
<?php echo $form->labelEx($model,'brand'); ?>
<?php echo $form->textField($model,'brand',array('size'=>30,'maxlength'=>30)); ?>
<?php echo $form->error($model,'brand'); ?>
<?php echo $form->labelEx($model,'price'); ?>
<?php echo $form->textField($model,'price'); ?>
<?php echo $form->error($model,'price'); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
<?php $this->endWidget(); ?>
can someone PLEASE tell me how can i achieve this . Thank you
try with
array('name, category, model, brand, description, price', 'required'),
array('pimg', 'file','types'=>'jpg','on'=>'insert', 'allowEmpty'=>false),
array('pimg', 'file','types'=>'jpg','on'=>'update', 'allowEmpty'=>true),
if you redirect a page, the error will not be shown,
your code redirects anyway, if (save()) or not .
add a {} after your if
if($model->save())
{
$model->pimg->saveAs('images/'.$fileName);
$this->redirect(array('display','id'=>$model->productid));
}

CForm and its behaviors do not have a method or closure named "beginWidget"

I am quite new in using Yii Fraework and I am trying to implement a custom form with the skeletron from the contact form demo withon the blog demo from Yii Framework. I did almost exactly the same view,, controller and model as the respective form, only that I get the following 500 error:
Error 500
CForm and its behaviors do not have a method or closure named "beginWidget".
Here are the : Controller:
<?php
class CustomController extends Controller {
public function actionSubmit()
{
$model = new CustomForm;
$form = new CForm('application.views.custom._form', $model);
$this->pageTitle = "ffffffffffff";//['title'] = "Authentication";
if($form->submitted('submit') && $form->validate())
$this->redirect(array('blog/index'));
else
$this->render('_form', array('form'=>$form));
}
public function getGenders()
{
return array(
0 => 'Male',
1 => 'Female');
}
}
?>
The Model:
<?php
class CustomForm extends CFormModel {
public $firstName;
public $LastName;
public $phone;
public $address;
public $gender;
public $email;
public function rules()
{
return array(
array('firstName, lastName, gender', 'required'),
array('email', 'email')
);
}
}
?>
The view:
<?php
$this->pageTitle=Yii::app()->name . ' - Custom Form';
$this->breadcrumbs=array(
'Custom Form',
);
?>
<h1>Custom Form</h1>
<?php if(Yii::app()->user->hasFlash('custom')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('custom'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'custom-form',
)); ?>
<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,'firstName'); ?>
<?php echo $form->textField($model,'firstName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'phone'); ?>
<?php echo $form->textField($model,'phone',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'gender'); ?>
<?php echo $form->radioButton($model,'gender',array('value'=>'Male')) . 'Male'; ?>
<?php echo $form->radioButton($model,'gender',array('value'=>'Female')) . 'Female'; ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'address'); ?>
<?php echo $form->textArea($model,'address',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Any ideas why am I getting this error? What am I doing wrong?
Thanks!
CForm represents a form object that contains form input specifications.
You are passing a view file as parameter to the CForm which wont work.
I guess there is no need for this line:
$form = new CForm('application.views.custom._form', $model);
Please check if it works :)

Categories