yii not saving model - php

$model=new Event('create');
$model->attributes=$_POST['Event'];
if($model->save()){
$pkg = new Package();
$pkg->attributes=$_POST['Package'];
$pkg->event_id = $model->id;
$pkg->save();
}
The Event model gets saved correctly with all the POST variables for Event, while the Package only has the event_id set, but no attributes are set (they are all NULL). What am I doing wrong?
NB: The Event object has been programmed by my predecessor, the Package object is a new addition I did.
EDIT: the whole Package class
class Package extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'tbl_package';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('', 'safe', 'on'=>'search'),
array('', 'numerical'),
);
}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(
'event' => array(self::BELONGS_TO, 'Event', 'id')
);
}public function attributeLabels()
{
return array(
'event_id' => 'Event ID',
'package_name' => 'Package name',
'event_banner' => 'Event Banner',
'ad_placement' => 'Ad Placement in Event Program',
'logo_on_step' => 'Logo on Step & Repeat',
'use_evt_pics' => 'Usage of Event Pictures',
'exhibition' => 'Exhibition Booth/Space',
'inc_press' => 'Inclusion in Press',
'print_ads' => 'Insertion in Print Ads',
'online_ads' => 'Insertion in Online Ads',
'attendee_bags' => 'Attendee Bags',
'charging_st' => 'Charging Stations',
'cups' => 'Coffee/Water Cups',
'distr_items' => 'Distributable Items',
'lanyards' => 'Lanyards',
'napkins' => 'Napkins',
'notebooks' => 'Notebooks',
'pens' => 'Pens',
'seat_covers' => 'Seat Covers',
'snack_pack' => 'Snack Packaging',
'water_bottles' => 'Water Bottles'
);
} public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('event_banner',$this->event_banner);
$criteria->compare('package_name',$this->package_name);
$criteria->compare('ad_placement',$this->ad_placement);
$criteria->compare('logo_on_step',$this->logo_on_step);
$criteria->compare('use_evt_pics',$this->use_evt_pics);
$criteria->compare('exhibition',$this->exhibition);
$criteria->compare('inc_press',$this->inc_press);
$criteria->compare('print_ads',$this->print_ads);
$criteria->compare('online_ads',$this->online_ads);
$criteria->compare('attendee_bags',$this->attendee_bags);
$criteria->compare('charging_st',$this->charging_st);
$criteria->compare('cups',$this->cups);
$criteria->compare('distr_items',$this->distr_items);
$criteria->compare('lanyards',$this->lanyards);
$criteria->compare('napkins',$this->napkins);
$criteria->compare('notebooks',$this->notebooks);
$criteria->compare('pens',$this->pens);
$criteria->compare('seat_covers',$this->seat_covers);
$criteria->compare('snack_pack',$this->snack_pack);
$criteria->compare('water_bottles',$this->water_bottles);
return new CActiveDataProvider('SponsorshipPackage', array(
'criteria'=>$criteria,
));
}
}

If you want to set attributes through:
$pkg->attributes=$_POST['Package'];
then you have to set rules for any attribute that can be set this way.
You need something like this:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('package_name', 'required'),
array('package_name', 'length', 'max' => 255),
// or
array('package_name', 'length', 'max' => 255, 'on' => 'insert'),
// at least (when no validation is required):
array('package_name', 'safe'),
// ...
// and so on..
);
}
you need rule for any attribute that you want to set this way.
if there is no rule set for attribute you'll be able to set its value only through $pkg->attribute_name = $value;
rule like array('', 'safe', 'on'=>'search'), or array('', 'numerical'), does nothing (cause attributes list is empty).
read more about validation here

class Package extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'tbl_package';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('ad_placement, logo_on_step, ...', 'safe', 'on'=>'search'), //note put here all attrs name that you feel those attrs needs to be assigned from POST like: `$pkg->attributes=$_POST['Package'];`
array('event_id', 'numerical'),
);
}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(
'event' => array(self::BELONGS_TO, 'Event', 'id')
);
}public function attributeLabels()
{
return array(
'event_id' => 'Event ID',
'package_name' => 'Package name',
'event_banner' => 'Event Banner',
'ad_placement' => 'Ad Placement in Event Program',
'logo_on_step' => 'Logo on Step & Repeat',
'use_evt_pics' => 'Usage of Event Pictures',
'exhibition' => 'Exhibition Booth/Space',
'inc_press' => 'Inclusion in Press',
'print_ads' => 'Insertion in Print Ads',
'online_ads' => 'Insertion in Online Ads',
'attendee_bags' => 'Attendee Bags',
'charging_st' => 'Charging Stations',
'cups' => 'Coffee/Water Cups',
'distr_items' => 'Distributable Items',
'lanyards' => 'Lanyards',
'napkins' => 'Napkins',
'notebooks' => 'Notebooks',
'pens' => 'Pens',
'seat_covers' => 'Seat Covers',
'snack_pack' => 'Snack Packaging',
'water_bottles' => 'Water Bottles'
);
}
....
}
If it does not work, then you may try, htere is validate() method before save():
$model=new Event('create');
$model->attributes=$_POST['Event'];
if($model->validate()){
$model->save();
}
else{
echo CHtml::errorSummary($model);
}
This will tell what is error.
Never save direct, validate it before save.

Related

Why Yii Criteria does not work directly?

The following Criteria works fine:
$criteria = new CDbCriteria(array(
'condition' => 'Id_menu = 1 ',
'select' => 'name',
'limit' => 5,
));
$dp1 = new CActiveDataProvider('post', array(
'criteria' => $criteria
));
However specifying Criteria directly on a model does not - it has no effect:
$criteria = new CDbCriteria(array(
'condition' => 'Id_menu = 1 ',
'select' => 'name',
'limit' => 5,
));
$dp1 = new CActiveDataProvider(Mdlfood::model()->find($criteria),array(),));
The following also does not work:
$criteria = new CDbCriteria(array(
'condition' => 'Id_menu = 1 ',
'select' => 'name',
'limit' => 5,
));
$model1 = new Mdlfood;
$model1->findAll($criteria);
$dp1 = new CActiveDataProvider($model1,array(),));
Can anyone explain why I cannot declare this configuration directly?
Added mdlfood
class Mdlfood extends CActiveRecord{
public function tableName()
{
return 'tblfood';
}
public function rules()
{
return array(
array('name, Url_picture, Price, Aboute, Id_foodType, Id_menu', 'required'),
array('name', 'length', 'max'=>100),
array('Url_picture, Aboute', 'length', 'max'=>2048),
array('Price, Id_foodType, Id_menu', 'length', 'max'=>20),
array('Id, name, Url_picture, Price, Aboute, Id_foodType, Id_menu', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
'idMenu' => array(self::BELONGS_TO, 'Tblrestmenu', 'Id_menu'),
'idFoodType' => array(self::BELONGS_TO, 'Tblfoodtype', 'Id_foodType'),
);
}
public function attributeLabels()
{
return array(
'Id' => 'ID',
'name' => 'Name',
'Url_picture' => 'Url Picture',
'Price' => 'Price',
'Aboute' => 'Aboute',
'Id_foodType' => 'Id Food Type',
'Id_menu' => 'Id Menu',
);
}
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('Id',$this->Id,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('Url_picture',$this->Url_picture,true);
$criteria->compare('Price',$this->Price,true);
$criteria->compare('Aboute',$this->Aboute,true);
$criteria->compare('Id_foodType',$this->Id_foodType,true);
$criteria->compare('Id_menu',$this->Id_menu,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
But, I think this is not related to Model, because this Criteria work properly in the ActiveDataProvider.
Please try like this,
extra closing brackets, find()-> not in proper format
$criteria=new CDbCriteria(array(
'condition'=>'Id_menu = 1 ',
'select'=>'name',
'limit'=>5,
));
$dp1 = new CActiveDataProvider(Mdlfood::model()->find($criteria),array()); // extra closing brackets
Second way,
$criteria=new CDbCriteria(array(
'condition'=>'Id_menu = 1 ',
'select'=>'name',
'limit'=>5,
));
$model1 = new Mdlfood;
$model1->findAll($criteria);
$dp1 = new CActiveDataProvider($model1,array());

Yii model validation rules

An issue with yii validation rule, I have created a signup form with a coupon code for my product. When a user enters coupon code I want to check if the value is present in the coupon table or not.
When the user enter the couponcode I want my validation rule to work, otherwise, if user doesn't enter the code this validation rule should not work, for member signup, I have a member model and for coupon I have a coupon model,
I am using this method in validation rules.
class MemberSignup extends CActiveRecord
{
public $couponcode;
public function rules(){
array('couponcode', 'isCouponCodeExist'),
}//end rules
public function isCouponCodeExist($attribute, $params)
{
$record = Coupon::model()->findByAttributes(array('couponcode' => $this->couponcode));
if($record === null){
$this->addError($attribute, 'Invalid Coupon');
return false;
}
return true;
}
} //class end
any suggesstion will be helpfull for me
<?php
class MemberSignup extends CActiveRecord
{
public $confPassword;
public $couponcode;
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return MemberSignup the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'members';
}
/**
* #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('member_login, member_password,gateway_id, confPassword,email, first_name, packageid,agreed,trafficesource', 'required'),
array('couponcode', 'isCouponCodeExist'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('member_id, member_login', 'safe', 'on'=>'search'),
);
}
public function isCouponCodeExist($attribute,$params){
$record=Coupon::model()->findByAttributes(array('couponcode'=>$this->couponcode));
if($record===null){
$this->addError($attribute, 'Invalid Coupon');
}
}
/**
* #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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'member_id' => 'Member',
'member_login' => 'Username',
'user_id' => 'User',
'member_password' => 'Password',
'confPassword' =>'Confirm Password',
'member_level' => 'Member Level',
'affiliate_id' => 'Affiliate',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'address' => 'Address',
'city' => 'City',
'state' => 'State',
'country' => 'Country',
'zip' => 'Zip',
'home_phone' => 'Home Phone',
'work_phone' => 'Work Phone',
'refered_by' => 'Refered By',
'location' => 'Location',
'product_id' => 'Product',
'product_path' => 'Product Path',
'product_description' => 'Product Description',
'confirmation_hash' => 'Confirmation Hash',
'status' => 'Status',
'cancellation_reason' => 'Cancellation Reason',
'cancellation_date' => 'Cancellation Date',
'registration_date' => 'Registration Date',
'next_billingdate' => 'Next Billingdate',
'CC_no' => 'Cc No',
'CC_expiry' => 'Cc Expiry',
'last_login' => 'Last Login',
'total_rebillings' => 'Total Rebillings',
'ufa_list_size' => 'Ufa List Size',
'billing_amount' => 'Billing Amount',
'privilege' => 'Privilege',
'maximportlimit' => 'Maximportlimit',
'mailingcount' => 'Mailingcount',
'mailinglimit' => 'Mailinglimit',
'registration_ip' => 'Registration Ip',
'address2' => 'Address2',
'Reactivation_Note' => 'Reactivation Note',
'call_date' => 'Call Date',
'CC_last_four' => 'Cc Last Four',
'slidenumber' => 'Slidenumber',
'domain' => 'Domain',
'registerdomain' => 'Registerdomain',
'gb1_affilateID' => 'Gb1 Affilate',
'agreed' => 'Agreed',
'packageid' => 'Packageid',
'ppid' => 'Ppid',
'sendmeitemizedbill' => 'Sendmeitemizedbill',
'is_superstarmember' => 'Is Superstarmember',
'activationdate' => 'Activationdate',
'reactivationdate' => 'Reactivationdate',
'suspensiondate' => 'Suspensiondate',
'is_editor' => 'Is Editor',
'mobile_phone' => 'Mobile Phone',
'member_quta' => 'Member Quta',
'notification' => 'Notification',
'cancellationrequest' => 'Cancellationrequest',
'siteiD' => 'Sitei D',
'companyname' => 'Companyname',
'companywebsite' => 'Companywebsite',
's3_quota' => 'S3 Quota',
's3_quota_consume' => 'S3 Quota Consume',
'gateway_id' => 'Gateway',
'invoice_id' => 'Invoice',
'couponid' => 'Couponid',
'coupon_success' => 'Coupon Success',
'dont_cancel' => 'Dont Cancel',
'notes' => 'Notes',
'trafficesource' => 'Traffice Source',
'othersource' => 'Othersource',
'couponcode'=>'Coupon Code',
);
}
/**
* 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('member_id',$this->member_id);
$criteria->compare('member_login',$this->member_login,true);
$criteria->compare('user_id',$this->user_id);
$criteria->compare('member_password',$this->member_password,true);
$criteria->compare('member_level',$this->member_level);
$criteria->compare('affiliate_id',$this->affiliate_id,true);
$criteria->compare('first_name',$this->first_name,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('city',$this->city,true);
$criteria->compare('state',$this->state,true);
$criteria->compare('country',$this->country,true);
$criteria->compare('zip',$this->zip,true);
$criteria->compare('home_phone',$this->home_phone,true);
$criteria->compare('work_phone',$this->work_phone,true);
$criteria->compare('refered_by',$this->refered_by,true);
$criteria->compare('location',$this->location,true);
$criteria->compare('product_id',$this->product_id);
$criteria->compare('product_path',$this->product_path,true);
$criteria->compare('product_description',$this->product_description,true);
$criteria->compare('confirmation_hash',$this->confirmation_hash,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('cancellation_reason',$this->cancellation_reason,true);
$criteria->compare('cancellation_date',$this->cancellation_date,true);
$criteria->compare('registration_date',$this->registration_date,true);
$criteria->compare('next_billingdate',$this->next_billingdate,true);
$criteria->compare('CC_no',$this->CC_no,true);
$criteria->compare('CC_expiry',$this->CC_expiry,true);
$criteria->compare('last_login',$this->last_login,true);
$criteria->compare('total_rebillings',$this->total_rebillings);
$criteria->compare('ufa_list_size',$this->ufa_list_size);
$criteria->compare('billing_amount',$this->billing_amount);
$criteria->compare('privilege',$this->privilege,true);
$criteria->compare('maximportlimit',$this->maximportlimit);
$criteria->compare('mailingcount',$this->mailingcount,true);
$criteria->compare('mailinglimit',$this->mailinglimit,true);
$criteria->compare('registration_ip',$this->registration_ip,true);
$criteria->compare('address2',$this->address2,true);
$criteria->compare('Reactivation_Note',$this->Reactivation_Note,true);
$criteria->compare('call_date',$this->call_date,true);
$criteria->compare('CC_last_four',$this->CC_last_four,true);
$criteria->compare('slidenumber',$this->slidenumber,true);
$criteria->compare('domain',$this->domain,true);
$criteria->compare('registerdomain',$this->registerdomain,true);
$criteria->compare('gb1_affilateID',$this->gb1_affilateID,true);
$criteria->compare('agreed',$this->agreed,true);
$criteria->compare('packageid',$this->packageid);
$criteria->compare('ppid',$this->ppid);
$criteria->compare('sendmeitemizedbill',$this->sendmeitemizedbill,true);
$criteria->compare('is_superstarmember',$this->is_superstarmember);
$criteria->compare('activationdate',$this->activationdate,true);
$criteria->compare('reactivationdate',$this->reactivationdate,true);
$criteria->compare('suspensiondate',$this->suspensiondate,true);
$criteria->compare('is_editor',$this->is_editor);
$criteria->compare('mobile_phone',$this->mobile_phone,true);
$criteria->compare('member_quta',$this->member_quta,true);
$criteria->compare('notification',$this->notification,true);
$criteria->compare('cancellationrequest',$this->cancellationrequest,true);
$criteria->compare('siteiD',$this->siteiD);
$criteria->compare('companyname',$this->companyname,true);
$criteria->compare('companywebsite',$this->companywebsite,true);
$criteria->compare('s3_quota',$this->s3_quota);
$criteria->compare('s3_quota_consume',$this->s3_quota_consume);
$criteria->compare('gateway_id',$this->gateway_id,true);
$criteria->compare('invoice_id',$this->invoice_id);
$criteria->compare('couponid',$this->couponid);
$criteria->compare('coupon_success',$this->coupon_success);
$criteria->compare('dont_cancel',$this->dont_cancel);
$criteria->compare('notes',$this->notes,true);
$criteria->compare('trafficesource',$this->trafficesource,true);
$criteria->compare('othersource',$this->othersource,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
If I have understood you correctly, your couponcode is not required and you would like to validate the couponcode only if the user has entered one.
public function rules()
{
return array(
array('field1, field2, field3', 'required'),
array('couponcode', 'isCouponCodeExist'),
);
}
EDIT:
In yii, all validation methods in a model will be executed, even if the field that's being validated is not required. Even though your field couponcode is not required, the validation method isCouponCodeExist() will always be executed.
That means we'll have to edit your code in the method isCouponCodeExist() to allow an empty couponcode, a little something like this:
public function isCouponCodeExist($attribute, $params)
{
if(!empty($this->couponcode))
{
$record = Coupon::model()->findByAttributes(array('couponcode' => $this->couponcode));
if($record === null)
{
$this->addError($attribute, 'Invalid Coupon');
}
}
}
Also, you don't have to return true or false in validation methods. All you need to do is add an error if something is wrong.

Misunderstanding in Yii model

I have a problem that i can`t get throught.
I am trying to display information from relational table like this:
$dataProvider = PartnerSite::model()->with('siteCommercials')->findAll("user_id=" . Yii::app()->user->id);
$this->render('index', array(
'dataProvider' => $dataProvider,
'allMoney' => 1
));
But in my view i am seeing that error:
Relation "siteCommercials" is not defined in active record class "PartnerSite".
But the fact is that my model have relation:
public function relations() {
return array(
'goesFromSites' => array(self::HAS_MANY, 'GoesFromSite', 'site_id'),
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'siteCommercials' => array(self::HAS_MANY, 'SiteCommercial', 'site_id'),
);
}
So my question is. Is there is something wrong? I can't get it... In only one that model is a lot of problems... BeforeSave() doesn't work and relations work not well. User relation is working just fine.
Full listing of "model":
<?php
abstract class BasePartnerSite extends GxActiveRecord {
public $siteCommercials = "oke";
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return '{{partner_site}}';
}
public static function label($n = 1) {
return Yii::t('app', 'PartnerSite|PartnerSites', $n);
}
public static function representingColumn() {
return 'site_name';
}
public function rules() {
return array(
array('site_name', 'required'),
array('user_id', 'numerical', 'integerOnly'=>true),
array('site_name', 'length', 'max'=>255),
array('id, site_name, user_id', 'safe', 'on'=>'search'),
);
}
public function relations() {
return array(
'goesFromSites' => array(self::HAS_MANY, 'GoesFromSite', 'site_id'),
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'siteCommercials' => array(self::HAS_MANY, 'SiteCommercial', 'site_id'),
);
}
public function pivotModels() {
return array(
);
}
public function attributeLabels() {
return array(
'id' => Yii::t('app', 'ID'),
'site_name' => Yii::t('app', 'Site Name'),
'user_id' => null,
'goesFromSites' => null,
'user' => null,
'siteCommercials' => null,
);
}
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('site_name', $this->site_name, true);
$criteria->compare('user_id', $this->user_id);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
}
Your class is BasePartnerSite. In this class you define relation siteCommercials.
Your error message: "Relation "siteCommercials" is not defined in active record class "PartnerSite".
So then shouldn't your code be?
$dataProvider = BasePartnerSite::model()->with('siteCommercials')->findAll("user_id=" . Yii::app()->user->id);

Adding where close on Gii generated CRUD

I am beginner with Yii and I used GII to create a CURD table. Everything is working fine but I only want to fetch certain record from the database by putting a where clause (for example "where client gender is male). I cannot find where the data is fetched from the database in Gii's generated code and where I need to insert the WHERE clause in the code.
As you know the Gii generated Model, controller and view file. The model file is as below. My view used CGridView to generate the CRUD table.
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName() {
return 'test_prefixtbl_client_local';
}
/**
* #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('client_id', 'required'),
array('client_id', 'length', 'max' => 15),
array('surname, forename', 'length', 'max' => 20),
array('title', 'length', 'max' => 6),
array('status', 'length', 'max' => 8),
array('dob', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('client_id, surname, forename, title, status, dob', 'safe', 'on' => 'search'),
);
}
/**
* #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(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'client_id' => 'Client ID',
'surname' => 'Surname',
'forename' => 'Forename',
'title' => 'Title',
'status' => 'Status',
'dob' => 'Date of birth (yyyy-mm-dd)',
'actions' => 'Actions',
);
}
/**
* 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('client_id', $this->client_id, true);
$criteria->compare('surname', $this->surname, true);
$criteria->compare('forename', $this->forename, true);
$criteria->compare('title', $this->title, true);
$criteria->compare('status', $this->status, true);
$criteria->compare('dob', $this->dob, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'dob DESC',
),
));
}
You have two ways to do your query, one using Query Builder (tutorial here) like this:
$clientLocalArray = Yii::app()->db->createCommand()
->select()
->from("test_prefixtbl_client_local")
->where("gender = :gender", array(":gender"=>$gender))
->queryAll();
Or you can use the Active Record itself (tutorial here) like this:
$clientLocalArrayObjects = ClientLocal::model()->findAllByAttributes(array(
"gender" => $gender
));
Any doubts, just ask! :)

Yii Creating a Create & Update MVC with unrelated tables

So I have schemca very similiar to:
users
--------------
userid, name, password, email
userinroles
--------------
pk, userid, roleid
roles
-----------
roleid, level, description
As you can see the roles table is related to the users via the userinroles table, this is so a user can have edit rights within various groups and have different levels of access for different things. For example they might need to be a page editor while having a super admin rights on a module.
The problem is when I'm updating or creating a record I don't know how to list the roles such that you can check a box to what role they should have and insert that into the userinroles table.
Any ideas on how to do this?
Model:
Yii::import('application.models._base.BaseUser');
class User extends BaseUser
{
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function rules() {
return array(
array('username, password, email', 'required'),
array('isActive, isDeleted, isLocked', 'numerical', 'integerOnly'=>true),
array('username', 'length', 'max'=>50),
// Throws error if user name is not unique
array('username', 'unique', 'attributeName'=> 'username', 'caseSensitive' => 'false'),
array('password', 'length', 'max'=>255),
array('email, organization, position', 'length', 'max'=>100),
array('salt', 'length', 'max'=>32),
array('organization, position, salt, isActive, isDeleted, isLocked', 'default', 'setOnEmpty' => true, 'value' => null),
array('userid, username, password, email, organization, position, salt, isActive, isDeleted, isLocked', 'safe', 'on'=>'search'),
);
}
public function relations() {
return array(
'toolaccesses' => array(self::HAS_MANY, 'Toolaccess', 'userID'),
'usergalleries' => array(self::HAS_MANY, 'Usergallery', 'userid'),
'userinroles' => array(self::HAS_MANY, 'Userinroles', 'userid'),
'tools' =>array(self::MANY_MANY, 'Tool', 'toolid'),
);
}
}
Controller:
class UserController extends GxController {
public function actionView($id) {
$this->render('view', array(
'model' => $this->loadModel($id, 'User'),
));
}
public function actionCreate() {
$model = new User;
if (isset($_POST['User'])) {
$model->setAttributes($_POST['User']);
// salting the user's password before we insert
$model->password = md5(Yii::app()->params["salt"] . $model->password);
if ($model->save()) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->userid));
}
}
$this->render('create', array( 'model' => $model));
}
public function actionUpdate($id) {
$model = $this->loadModel($id, 'User');
if (isset($_POST['User'])) {
// testing if we need to salt the password.
if(strcmp($_POST['User']['password'], $model->password)!=0)
{ // passwords passed in are not the same. We need to now modify the post password
$_POST['User']['password'] = md5(Yii::app()->params["salt"] . $_POST['User']['password']);
}
$model->setAttributes($_POST['User']);
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->userid));
}
}
$this->render('update', array(
'model' => $model,
));
}
public function actionDelete($id) {
// prevent the deletion of the super user, who has the ID 1.
// This is sort of like a Unix "root" user or a Window's Administrator
if($id == 1)
{
throw new CHttpException(400, Yii::t('app', 'You cannot delete the super admin.'));
}
else
{
if (Yii::app()->getRequest()->getIsPostRequest()) {
$this->loadModel($id, 'User')->delete();
if (!Yii::app()->getRequest()->getIsAjaxRequest())
$this->redirect(array('admin'));
} else
throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
}
}
public function actionIndex() {
$dataProvider = new CActiveDataProvider('User');
$this->render('index', array(
'dataProvider' => $dataProvider,
));
}
public function actionAdmin() {
$model = new User('search');
$model->unsetAttributes();
if (isset($_GET['User']))
$model->setAttributes($_GET['User']);
$this->render('admin', array(
'model' => $model,
));
}
}
First, I think you should use Many-Many relation between users and roles table -
public function relations() {
return array(
'toolaccesses' => array(self::HAS_MANY, 'Toolaccess', 'userID'),
'usergalleries' => array(self::HAS_MANY, 'Usergallery', 'userid'),
'roles' => array(self::MANY_MANY, 'Roles', 'userinroles(userid, roleid)'),
'tools' => array(self::MANY_MANY, 'Tool', 'toolid'),
);
After that, you will able to get roles for users with $user->roles. About some actions with roles, related to concrete user: i use this extension to save many-many relations. Sorry if i understood you wrong.

Categories