I'm new to YII. I created a table with text fields and created model and crud generators, I created text fields for dates. Then I replaced it with datepicker, but I don't know how to connect my new datepicker with model.
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, gender, age, dob, doj, class,
no_seats, train_name, proof_1, proof_2, proof_3', 'required'),
array('age, class, no_seats', 'numerical', 'integerOnly'=>true),
array('name', 'length', 'max'=>20),
array('gender', 'length', 'max'=>6),
array('train_name', 'length', 'max'=>23),
//I created the below statement instead of the previous //one
//created for text field but it is not working
array('dob','date','format'=>Yii::app()->
locale->getDateFormat('medium')),
array('proof_1', 'length', 'max'=>7),
array('proof_2', 'length', 'max'=>8),
array('proof_3', 'length', 'max'=>9),
array('status', 'length', 'max'=>1),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('refid, name, gender, age, dob, doj,
class, no_seats, train_name, proof_1, proof_2,
proof_3, created, lastmodified, status', 'safe', 'on'=>'search'),
);
}
// View
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
// add to Model rules
array('date', 'type', 'type'=>'date', 'dateFormat'=>'dd-MM-yy'),
You can use a datepicker widget like the following in place of any text input attribute you have. This will create correct fields in the form and in $_POST, and is ready to be manipulated by model functions. Note that there is a validator 'date' that you can put in rules for your model. You should have the same dateFormat in the widget and in the rules.
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
Since you were specifically asking about the rules:
public function rules()
{return array(
array('date_field', 'date'),
);}
Here is a good summary for validators:
http://www.yiiframework.com/wiki/56/
Related
I'm having problem to show data on cgridview using foreign keys.
This is my case, i have table employee(id, username), client(id, username), and transaction(id, employeeId, clientId). employeeId foreign key to employee.id, and clientId is foreign key to client.id. Now, I want to show employee's name and client's name instead of their id on transaction admin.php.
This is my code:
class Transaction extends CActiveRecord
{
public $client_search;
public $employee_search;
public function rules()
{
return array(
.
.
.
array('id, employeeId, clientId, balance, status, date, client_search, employee_search', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'employee' => array(self::BELONGS_TO, 'Employee', 'employeeId'),
'client' => array(self::BELONGS_TO, 'Client', 'clientId'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array( 'client', 'employee' );
$criteria->together = true;
$criteria->compare('t.id',$this->id,true);
$criteria->compare('employee.username', $this->employee_search, true );
$criteria->compare('client.username', $this->client_search, true );
$criteria->compare('t.balance',$this->balance,true);
$criteria->compare('t.status',$this->status);
$criteria->compare('t.date',$this->date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
//the other functions are there, i don't edit it.
}
that is my model/Transaction.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'transaction-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
array(
'header' => 'Employee',
'name' => 'employee_search',
'value' => '$data->employee->username',
),
array(
'header' => 'Client',
'name' => 'client_search',
'value' => '$data->client->username',
),
array(
'class'=>'CButtonColumn',
),
),
));
that is my views/transaction/admin.php.
and this code gave me error Trying to get property of non-object ($data->employee->id marked).
Actually I have succed to show the employee's name instead of employee's id, but, after that I use the same method for the client, and the error appear.
anyone can help me? My method is making public employee_search, add the rules, add the relation, adding $creiteria->with, then change the admin.php. Anyone please help me.
//UPDATE
SOLVED. Its actually my fault. There is an error in the database about the relation (foreign key). My coding is fine.
It's hard to guess without being able to debug your code but here are some things that could help (I'll add more as I can think of them).
It might be because both the default joinType for relations is LEFT OUTER JOIN and maybe you have a Transaction where one of them is null? If you try to access attributes on null object (as opposed to an actual ActiveRecord object), that's precisely the error message you would be seeing.
You could change it by doing:
public function relations()
{
return array(
'employee' => array(self::BELONGS_TO, 'Employee', 'employeeId',array('joinType'=>'INNER JOIN')),
'client' => array(self::BELONGS_TO, 'Client', 'clientId',array('joinType'=>'INNER JOIN')),
);
}
P.S.: INNER JOIN is the same as just JOIN
Not sure if it will help you, but it's worth trying.
More information at: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#relations-detail
I am a newbei in yii, when a person clicks on a category display him all products under that particular category in a gridview
view
productcategory
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'admin-grid',
'dataProvider'=>$model->SelectedCategoryProducts,
'filter'=>$model,
'columns'=>array(
'Name',
'Model',
'Brand',
'Price',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
controller
product
public function actionProductcategory($id)
{
$model= Product::model()->SelectedCategoryProducts($id);
var_dump($model);
$this->render('productcategory',array(
'model'=>$model,'id'=>$id,
));
}
model
product
public function SelectedCategoryProducts($id)
{
$dataProvider=new CActiveDataProvider('Product', array(
'criteria'=>array(
'select'=>'name,model,price,brand',
'condition'=>'category=:category',
'params'=>array(':category'=>$id),
)));
var_dump($dataProvider);
return $dataProvider;
}
CException
Property "CActiveDataProvider.sellerSelectedCategoryProducts" is not defined.
PLEASE HELP! I am losing my mind on this ... not able to display in gridview.
Pass $id to your view file.
$this->render('productcategory',array('model'=>$model,'id'=>$id));
Then pass id to model function in ccgridview function.
'dataProvider'=>$model->SelectedCategoryProducts($id),
Hope this might help
Controller file
public function actionProductcategory($id)
{
$model=new Product;
$this->render('productcategory',array('model'=>$model,
'id'=>$id));
}
In View file
'dataProvider'=>$model->SelectedCategoryProducts($id),
UPDATE 1
'columns'=>array(
'name',
'model',
'brand',
'price',
change them to lowercase which are your original column names
$dataProvider=new CActiveDataProvider('Product', array(
'criteria'=>array(
'select'=>'name,model,price,brand',
'condition'=>'category=:category',
'params'=>array(':category'=>$id),
)));
this can retrieve needed data.... first check that data is perfect ... is it right after that take second step....
CJUIDatePicker not filtering value for dd/mm/yyyy format but filtering if i gave DB date format manually like shown in image, I have attached all codes including View and Model for Search panel and Date Widget, Please look into this,
My Model Search(),
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('crm_base_contact_id',$this->crm_base_contact_id);
$criteria->compare('name',$this->name,true);
$Date = date('Y-m-d',strtotime($this->created)); // get proper Y-m-d
$startOfDay = $Date . ' 00:00:00'; // from start of the day
$endOfDay = $Date . ' 23:59:59'; // until end of the day
// the rows between these
$criteria->addBetweenCondition('created', strtotime($startOfDay) , strtotime($endOfDay) );
$criteria->compare('createdby',$this->createdby,true);
$criteria->compare('description',$this->description);
$criteria->compare('is_active',$this->is_active);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
My View for CGridView,
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'basecontact-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
array('class'=>'CButtonColumn',),
'name',
'crm_base_contact_id',
array(
'name'=>'is_active',
'filter'=>CHtml::dropDownList('Event[is_active]', '',
array(
''=>'',
'1'=>'Y',
'0'=>'N',
)
),
'value' =>'($data->is_active==1)?"Y":"N"',
),
'created',
'createdby',
'description',
),
)); ?>
My View Code for Search column,
<?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model'=>$model,
'id'=>'Search-Created',
'attribute'=>'created',
'options'=>array(
'dateFormat'=>'dd/mm/yy',
'showAnim'=>'fold',
'buttonImage'=>Yii::app()->baseUrl.'/images/icons.date.png',
'buttonImageOnly'=>true,
'buttonText'=>'',
'showAnim'=>'fold',
'showOn'=>'button',
'showButtonPanel'=>false,
),
));?>
you should probably change the date format. set it like this, 'dateFormat'=>'dd-mm-yy',
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'dob',
// additional javascript options for the date picker plugin
'options' => array(
'showAnim' => 'fold',
'dateFormat'=>'dd/mm/yyyy',
),
'htmlOptions' => array(
'style' => 'height:20px;'
),
));
Update:
In your model, define it as following, in my case dob is the attribute name. you can have your own instead.
This will change your dateformat from "dd/mm/yyyy" to "yyyy-mm-dd internally before you run any find.
Ref : http://www.yiiframework.com/doc/api/1.1/CActiveRecord#beforeFind-detail
protected function beforeFind()
{
$this->dob=date('Y-m-d', strtotime($this->dob));
parent::beforeFind();
}
update 2
Replace your search method with this,
public function search() {
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('crm_base_contact_id', $this->crm_base_contact_id);
$criteria->compare('name', $this->name, true);
$criteria->compare('created', '07/12/2013'); //date('Y-m-d', strtotime($this->created))
$criteria->compare('createdby', $this->createdby, true);
$criteria->compare('description', $this->description);
$criteria->compare('is_active', $this->is_active);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Update 3
change this line $criteria->compare('created', '07/12/2013'); to
$criteria->compare('created', date('Y-m-d', strtotime($this->created));
I've had a working registration/update model, I wanted to expand on my models so I added in a regex to the password field. I have checked the regex works online and even my client side validation shows it works, but the model refuses to save now. I'm not really sure why, could anyone help me out please?
return array(
array('firstName, lastName, email, password', 'required'),
array('firstName', 'length', 'max'=>45),
array('lastName', 'length', 'max'=>80),
array('email', 'length', 'max'=>120),
// email must be valid email
array('email', 'email'),
// email must be unique
array('email', 'unique'),
// Regex for password
array('password','match', 'pattern'=>'/^[a-z0-9_-]{7,20}$/i',
'message'=>'The password must be between 7 and 20 characters
long'),
array('password', 'length', 'min'=>7, 'max'=>64),
array('date_modified', 'safe'),
array('active, date_modified', 'default', 'setOnEmpty' => true, 'value' => null),
array('id, first_name, last_name, email, pass, active, date_created, date_modified, live', 'safe', 'on'=>'search'),
);
Thanks
Jonny
You can create your own validation rule.
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
Or else you can define validation rule in YII Model, something like this:
return array(
array('password', 'length', 'min'=>7, 'max'=>64),
array('password','pattern'=>'/^[A-Za-z0-9_!##$%^&*()+=?.,]+$/u', 'message'=>'Spaces or given characters are not allowed'),
);
There are more validation you can specify in your model.
I have a database containing 3 tables, countries, cities and datacenters. country is the parent of city and city is the parent of datacenter. In the cities I have added a search dropdown of countries and its working fine. I have added cites search dropdown in datacenters and its also working fine but now i want countries search dropdown in datacenters, how to do it.
Code in datacenters for countries search dropdown in admin.php.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'data-centers-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'city.cityname'=>array(
'name'=>'cityid',
'value'=>'$data->city->cityname',
'filter'=>CHtml::listData(Cities::model()->findAll(array('order'=>'cityname')), 'id', 'cityname')
),
'city.country.countryname'=>array(
'name'=>'city.country.id',
'value'=>'$data->city->countryid',
'filter'=>CHtml::listData(Countries::model()->findAll(array('order'=>'countryname')), 'id', 'countryname')
),
'datacentername',
'datacentercode',
'lastupdatedon',
'createdon',
array(
'class'=>'CButtonColumn',
'template'=> '{view}{update}',
),
),
)); ?>
model code:
class DataCenters extends CActiveRecord
{
[...]
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'lastupdatedby0' => array(self::BELONGS_TO, 'Users', 'lastupdatedby'),
'city' => array(self::BELONGS_TO, 'Cities', 'cityid'),
'servers' => array(self::HAS_MANY, 'Servers', 'datacenterid'),
);
}
[...]
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('cityid',$this->cityid);
$criteria->compare('datacentername',$this->datacentername,true);
$criteria->compare('datacentercode',$this->datacentercode,true);
$criteria->compare('lastupdatedon',$this->lastupdatedon,true);
$criteria->compare('lastupdatedby',$this->lastupdatedby);
$criteria->compare('createdon',$this->createdon,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
[...]
}