Yii Creating a Create & Update MVC with unrelated tables - php

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.

Related

Update Profile yii framework

i want to build a update profile page, and i have 2 mysql table 1. account 2. info, so i want to insert or update the user info table.
this is what i have so far, but its return an error when saving the data "Call to undefined method stdClass::save()"
controller:
public function actionUpdate_profile() {
$model = new UserProfileForm();
$user = Userinfo::model()->findByPk(Yii::app()->user->id);
$model->name = $user->_name;
$model->myurl = $user->myurl;
if (isset($_POST['UserProfileForm'])) {
$model->attributes = $_POST['UserProfileForm'];
if ($model->validate()) {
$model->attributes = $_POST['UserProfileForm'];
$user->name = $model->name;
$user->myurl = $model->myurl;
$user->save();
});
});
$this->render('update_profile', array(
'model' => $model,
'user' => $user,
));
}
model:
class Userinfo extends CActiveRecord {
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'user_info';
}
public function rules() {
return array(
array('email, name, myurl', 'length', 'max' => 255),
);
}
public function attributeLabels() {
return array(
'user_id' => Yii::t('yii', 'Id User'),
'name' => Yii::t('yii', 'First Name'),
'myurl' => Yii::t('yii', 'Last Name'),
);
}
class UserProfileForm extends CFormModel {
public $name;
public $myurl;
public function rules() {
return array(
array('name, myurl', 'required'),
);
}
public function attributeLabels() {
return array(
'name' => Yii::t('yii', 'First Name'),
'myurl' => Yii::t('yii', 'Last Name'),
);
}
}
I know this not best practice but it is concise -
if($user = Userinfo::model()->findByPk(Yii::app()->user->id)) {
//then work with $user here
}

Not inserting the value in one column in db using yii

I am new to YII. Problem is that I am having issue s in entering the user record. It is not inserting the complete record in db. skipping last field. Below are my controller and model. It is not inserting the $heard_about_us in database.
class UsersController extends Karmora
user controller action
public function actionSignUp($affusername=null)
{
//echo "all is well";exit;
if(!empty($affusername)){
$this->VarifyUser($affusername);
$user_data = Users::model()->getUsersByUserName($affusername); //getting user information
}
else {
$user_data = '';
}
//echo '<pre>'; print_r($user_data); exit;
$this->ticker_news = NewsTicker::model()->getTickerNews();
$model=new Users('signup'); //apply rules if user comes directly to signup page
//echo '<pre>'; print_r($model); exit;
// uncomment the following code to enable ajax-based validation
if(isset($_POST['ajax']) && $_POST['ajax']==='users-signup-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$referrer_data="";
if(empty($affusername))
$referrer_data = $model->getUsersByRole("SuperAdmin");
else{
$referrer_data = $model->getUsersByUserName($affusername);
//if invalid affiliate name then redirect to home page
if(!$referrer_data) {
$this->redirect($this->base_url.'/home');
}
}
if(isset($_POST['Users']))
{
$_POST['Users']['optin'] = 0;
$_POST['Users']['registration_date'] = date('y-m-d h:i:s');
$_POST['Users']['role'] = "Affiliate";
$_SESSION['newUser'] = $_POST['Users'];
$model->attributes=$_POST['Users'];
if($model->validate())
{
//assigning referral key to new created user
$model->referrer = $referrer_data['id'];
$model->state = $_POST['Users']['state'];
// $model->subid = uniqid();
/*
$this->displayData($_POST);
exit;
*/
/*
Yii::import('application.vendors.*');
require_once('iPayout.php');
$config = array(
'MerchantGUID' => 'abcdefghi;dks;dfk',
'MerchantPassword' => 'password',
'eWalletAPIURL' => "https://www.testewallet.com/eWalletWS/ws_adapter.aspx"
);
$iPayout_obj = new iPayout($config);
$response = $iPayout_obj->iPayout_GetUniqueUserName(array('UserName'=>$_POST['Users']['username']));
//echo $response;
$check_username = json_decode($response);
$model->ewallet_username = $check_username->valid_user_name;
*/
// Jan 17, 2014, By IK, added new API
// Import Authorize.Net SDK from vendors
Yii::import('application.vendors/anet_php_sdk.*');
require_once('AuthorizeNet.php');
// If coupon code then
$trial = false;
if ($_POST['Users']['token']) {
$trial = true;
}
/* Authorize.Net test credit card numbers
- American Express Test Card: 370000000000002
- Discover Test Card: 6011000000000012
- Visa Test Card: 4007000000027
- Second Visa Test Card: 4012888818888
- JCB: 3088000000000017
- Diners Club/ Carte Blanche: 38000000000006*/
// Set the subscription fields.
$amount = 25;
$subscription = new AuthorizeNet_Subscription();
$subscription->name = $_POST['Users']['username']; //Merchant-assigned name for the subscription
$subscription->intervalLength = "1";
//$subscription->refId = "willid";
$subscription->intervalUnit = "months";
$subscription->startDate = date('Y-m-d'); //(YYYY-MM-DD) "2014-02-12";
$subscription->totalOccurrences = "9999";
$subscription->amount = $amount;
if ($trial) {
$subscription->trialOccurrences = "3";
$subscription->trialAmount = "0";
}
$subscription->creditCardCardNumber = $_POST['Users']["cardNumber"];
$subscription->creditCardExpirationDate = $_POST['Users']["exp_year"].'-'.$_POST['Users']["exp_month"]; //"2015-10";
$subscription->creditCardCardCode = $_POST['Users']["cardCode"];
$subscription->billToFirstName = $_POST['Users']["first_name"];
$subscription->billToLastName = $_POST['Users']["last_name"];
// Create the subscription.
$request = new AuthorizeNetARB(API_LOGIN_NAME, API_TRANSACTION_KEY);
$response = $request->createSubscription($subscription);
$isOk = $response->isOk();
// Payment is successfull and create user account
if ($isOk) {
// Authorize.Net Subscription id
$subscription_id = $response->getSubscriptionId();
if ($model->save()){
/******* Create blog ************/
$user_id = yii::app()->db->lastInsertID;
Yii::app()->session['username'] = $_POST['Users']['username'];
yii::app()->session['user_id'] = $user_id;
yii::app()->session['first_name'] = $_POST['Users']['first_name'];
yii::app()->session['email'] = $_POST['Users']['email'];
Yii::app()->session['password'] = $_POST['Users']['password'];
$db_user_data = $model->findByPk($user_id);
if(!(Users::model()->updateAll(array("status" => "active", "subid" => $subscription_id), "id = $user_id"))) {
//echo 'user not updated';
}
// Jan 17, 2014, Commented by IK, old Authorize.net is replaced by Authorize.Net SDK
/*
Yii::import('application.vendors.*');
require_once('karmora_authorizenet.php');
$config = array(
'loginname' => '8QqN8Q9p4P',
'transactionkey' => '7653C9N3VumpMn26',
'host' => "apitest.authorize.net",
'path' => "/xml/v1/request.api"
);
$kauthnet_obj = new karmora_authorizenet($config);
$authnet_data['amount'] = '25.0';
$authnet_data['refId'] = $db_user_data["subid"];
$authnet_data['name'] = $db_user_data["username"]; //Merchant-assigned name for the subscription
$authnet_data['length'] = 1;
$authnet_data['unit'] = 'months';
$authnet_data['startDate'] = date('Y-m-d'); //2013-11-05 (YYYY-MM-DD)
$authnet_data['totalOccurrences'] = '9999';
//$authnet_data['trialOccurrences'] = 2;
//$authnet_data['trialAmount'] = 0;
$authnet_data['cardNumber'] = $_POST['Users']["cardNumber"];
$authnet_data['expirationDate'] = $_POST['Users']["exp_year"].'-'.$_POST['Users']["exp_month"];
$authnet_data['firstName'] = $db_user_data["first_name"];
$authnet_data['lastName'] = $db_user_data["last_name"];
$con = $kauthnet_obj->setARBContent($authnet_data);
//print_r($con);
//print_r($kauthnet_obj);
$subscription_create = $kauthnet_obj->createARBSubscription();
*/
/*
Array
(
[refId] => 529722f838d54
[resultCode] => Ok
[code] => I00001
[text] => Successful.
[subscriptionId] => 1895540
)
*/
/******* Authorize.net END **********/
/* Commented by IK, we don't need blog at the moment
* Jan 10, 2014
* Blog creation login is not working at the moment due to some bug
*/
// Create blog
//$is_created = $this->CreateBlog($db_user_data);
/*if($is_created){
//echo 'BLOG CREATED';exit;
$this->updatedBlogUserStatus();
$this->redirect($this->base_url.'/videos');
}
else{
$subject = "Blog not created for user";
$message = "Error while creating a blog for following user<br><br>";
$message.="<b>User Detail:</b><br>";
$message.="Username: ".$db_user_data['username']."<br>";
$message.="Email: ".$db_user_data['email']."<br>";
$this->SendKarmoraMail($subject, $message, 'irfan.k#dprodigy.com');
//mail($to,$subject,$message,$headers)
}*/
/********** end create blog *****************/
$Loginmodel=new LoginForm();
$LoginFormData['username'] = $_POST['Users']['username'];
$LoginFormData['password'] = $_POST['Users']['password'];
//print_r($LoginFormData);
$Loginmodel->attributes=$LoginFormData;
if(!($Loginmodel->validate() && $Loginmodel->login())){
//echo 'Login failed';
$this->redirect($this->base_url); // Uncomment later
}
else if($Loginmodel->validate() && $Loginmodel->login()) {
$this->redirect($this->base_url.'/congrats'); // Uncomment later
//self::actionSignupCongrats();
}
}
else {
$this->setFlashError("Unable to register user, please try again");
return false;
}
}
else {
$error_text = $response->getResponseText();
$error_code = $response->getResponseCode();
if ($error_code == 'E00003') {
$error_text = 'Credit card number is invalid';
}
// Add custom error messages
$model->addError('cardNumber', $error_text);
}
}
else {
//echo '<pre>'; print_r($model->errors); echo '</pre>';exit;
}
}
$this->render('signup', array('model'=>$model, 'referrer_data' => $referrer_data, 'user_profile2' => $user_data));
}
}
User model is
<?php
if ( ! defined('YII_PATH')) exit('No direct script access allowed');
class Users extends CActiveRecord
{
//variable to confirm passwords
public $repeat_password;
public $agree_terms;
public $agree_referring_affiliate;
public $agree_subscription;
public $verifyCode;
public $referrer;
public $subid;
public $token;
public $cardNumber;
public $cardCode;
public $exp_year;
public $exp_month;
public $heard_about_us;
public $agree_refund_policy;
public $agree_subscription_cancel;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'users';
}
public function beforeSave(){
if(parent::beforeSave()){
// for example
if(!empty($this->password))
$this->password = crypt($this->password, '$1$rasmusle$'); // if you save dates as INT
//echo 'password: '.$this->password;exit;
return true;
}
else
return false;
}
/**
* #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('first_name, last_name, email, phone_no, country, heard_about_us, state, city, zipcode, gender, username, password, registration_date, optin, role, cardNumber, cardCode, exp_year, exp_month', 'required', 'on' => 'signup'),
array('first_name, last_name, email, phone_no, country, state, city, zipcode ', 'required','on'=>'edit'),
array('token', 'validateToken', 'on' => 'signup'),
array('is_fb, optin, referrer', 'numerical', 'integerOnly'=>true),
array('first_name, last_name, email, city, country', 'length', 'max'=>45),
array('username', 'length', 'max'=>20),
array('username', 'match', 'pattern'=>'/^([a-zA-Z0-9_])+$/', 'message' => 'Username should be alphanumeric and can contain "_" only'),
array('email', 'email'),
array('email, username', 'unique', 'on' => 'signup'),
array('password, address', 'length', 'max'=>128),
array('repeat_password', 'compare', 'compareAttribute'=>'password', 'message'=>'Passwords don\'t match'),
array('zipcode', 'length', 'max'=>7),
//array('image', 'length', 'max'=>255),
//array('image', 'file', 'types'=>'jpg, gif, png'),
array('status', 'length', 'max'=>8),
array('cardNumber', 'numerical', 'integerOnly'=>true),
array('cardNumber', 'length', 'min'=>13),
array('cardNumber', 'length', 'max'=>17),
array('cardNumber', 'match', 'pattern'=>'/^([0-9])+$/', 'message' => 'Credit Card Number should be numeric'),
array('cardCode', 'numerical', 'integerOnly'=>true),
array('cardCode', 'length', 'min'=>3),
array('cardCode', 'length', 'max'=>4),
array('cardCode', 'match', 'pattern'=>'/^([0-9])+$/', 'message' => 'Security Code (CVV) should be numeric'),
//array('exp_month', 'validateExpMonth', 'on' => 'signup'),
array('fb_id', 'length', 'max'=>250),
array('subid', 'unique'),
array('role', 'length', 'max'=>11),
array('last_login', 'safe'),
//array('exp_month', 'ext.validators.CardDateValidator', 'compareValue' => 'exp_year', 'message' => 'failure message'),
array('agree_refund_policy', 'required', 'message' => 'Please accept Karmora refund policy', 'on' => 'signup'),
array('agree_subscription', 'required', 'message' => 'Please accept Karmora subscription terms', 'on' => 'signup'),
array('agree_subscription_cancel', 'required', 'message' => 'Please accept Karmora subscription cancel terms', 'on' => 'signup'),
//array('agree_referring_affiliate', 'required', 'message' => 'Please accept Karmora referring affiliate terms', 'on' => 'signup'),
// Old terms and conditions are changed in new signup page design.
// array('agree_referring_affiliate', 'required', 'message' => 'Please accept Karmora referring affiliate terms', 'on' => 'signup'),
// array('agree_terms', 'required', 'message' => 'Please accept Karmora terms and conditions', 'on' => 'signup'),
// array('agree_subscription', 'required', 'message' => 'Please accept Karmora subscription terms', 'on' => 'signup'),
// verifyCode needs to be entered correctly
//array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements(), 'on' => 'signup'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, first_name, last_name, username, gender, heard_about_us, email, password, phone_no, registration_date, address, state, city, zipcode, country, image, status, last_login, is_fb, fb_id, optin, role', '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(
'favouriteProducts' => array(self::HAS_MANY, 'FavouriteProducts', 'user_id'),
'favouriteProducts1' => array(self::HAS_MANY, 'FavouriteProducts', 'user_id'),
'favourites' => array(self::HAS_MANY, 'Favourites', 'user_id'),
'reminders' => array(self::HAS_MANY, 'Reminder', 'user_id'),
'traningMaterialPurchases' => array(self::HAS_MANY, 'TraningMaterialPurchase', 'user_id'),
'userPayments' => array(self::HAS_MANY, 'UserPayments', 'user_id'),
'usersCommissions' => array(self::HAS_MANY, 'UsersCommission', 'user_referer'),
'usersCommissions1' => array(self::HAS_MANY, 'UsersCommission', 'user_referral'),
'usersReferences' => array(self::HAS_MANY, 'UsersReferences', 'user_id'),
'usersReferences1' => array(self::HAS_MANY, 'UsersReferences', 'referer_id'),
'usersTransactionsLogs' => array(self::HAS_MANY, 'UsersTransactionsLog', 'user_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'username' => 'Username',
'gender' => 'Gender',
'email' => 'Email',
'password' => 'Password',
'phone_no' => 'Phone No',
'registration_date' => 'Registration Date',
'address' => 'Address',
'state' => 'State',
'city' => 'City',
'zipcode' => 'Zipcode',
'country' => 'Country',
'image' => 'Image',
'status' => 'Status',
'last_login' => 'Last Login',
'is_fb' => 'Is Fb',
'fb_id' => 'Fb',
'optin' => 'Optin',
'role' => 'Role',
'heard_about_us' => 'Where You Heard About Us',
);
}
/**
* 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('first_name',$this->first_name,true);
$criteria->compare('last_name',$this->last_name,true);
$criteria->compare('username',$this->username,true);
$criteria->compare('gender',$this->gender,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('phone_no',$this->phone_no,true);
$criteria->compare('registration_date',$this->registration_date,true);
$criteria->compare('address',$this->address,true);
$criteria->compare('state',$this->state,true);
$criteria->compare('city',$this->city,true);
$criteria->compare('zipcode',$this->zipcode,true);
$criteria->compare('country',$this->country,true);
$criteria->compare('image',$this->image,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('last_login',$this->last_login,true);
$criteria->compare('is_fb',$this->is_fb);
$criteria->compare('fb_id',$this->fb_id,true);
$criteria->compare('optin',$this->optin);
$criteria->compare('role',$this->role,true);
$criteria->compare('heard_about_us',$this->heard_about_us,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/*
public function CardDateValidator($attribute,$params){
$cur_year = date('Y');
if($this->compareValue == $cur_year){
$cut_month = date('m');
}
if($cut_month){
$js = '
if($.trim(value)<"' . $cut_month . '") {
messages.push("' . $this->message . '");
}
';
return $js;
}
}*/
public function validateToken($attribute,$params){
$token = $this->token;
if(!empty($token)){
$command = yii::app()->db->createCommand();
$admin_data = $command->select('*')
->from('fundraising_tokens')
//->where('role:user_role', array(':user_role' => $user_role))
->where("token='". $token."' AND used_by <= 1" )
->queryRow();
if(!$admin_data)
$this->addError($attribute, 'Invalid token number');
else
return true;
}
}
public function getUsersByRole($user_role){
$command = yii::app()->db->createCommand();
$admin_data = $command->select('*')
->from($this->tableName())
//->where('role:user_role', array(':user_role' => $user_role))
->where("role='". $user_role."'")
->queryRow();
if($admin_data)
return $admin_data;
else
return false;
}
public function getUsersByUserName($user_name){
$command = yii::app()->db->createCommand();
$admin_data = $command->select('*')
->from($this->tableName())
//->where('role:user_role', array(':user_role' => $user_role))
->where("username='". $user_name."'")
->queryRow();
if($admin_data)
return $admin_data;
else
return false;
}
public function getUserIdByUsername($username){
$detail = yii::app()->db->createCommand()
->select('u.id')
->from('users u')
->where('u.username=:username', array(':username'=>$username))
->queryAll();
if($detail)
return $detail[0];
else
return FALSE;
}
}
Make that attribute safe in model -> rules :
public function rules() {
return array(
// other rules
array('attribute_name_that_is_not_inserting', 'safe'),
);
}

Cakephp joining two models on insert

OKay so i have two tables Employee and User
my employee model looks like this:
class Employee extends AppModel{
public $name = 'Employee';
public $primaryKey = "employee_id";
public $actsAs = array('Containable');
public $belongsTo = array(
'User' => array(
'className' => 'User',
'dependent' => false,
'foreignKey' => 'user_id'
)
);
}
And my user model looks like this:
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
// ...
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('employee', 'client')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
In my employee controller i have an action that allows employees to add other employees the action looks like this:
public function add() {
if ($this->request->is('post')) {
$this->Employee->User->create();
if ($this->Employee->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
My employee table looks like this
employee_id user_id
Now whenever i add a user the user is correctly added in my user table and a row is also added in my employee table however there are two mistakes in the employee table:
The employee_id is an auto increment this does not happen and it seems it keeps overriting 1. (so that every user i try to create is employee_id = 1)
the user_id is always 0 however in the user table the user_id is for example 21.
Can anyone tell me why this is happening and how i can fix it?
update
My add action in my employee controller now looks like this:
public function add() {
if ($this->request->is('post')) {
$this->Employee->User->create();
if ($this->Employee->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
ive added a hasMany to my user model:
public $hasMany = array(
'Employee' =>array(
'className' => 'Employee',
'dependent' => true,
'foreignKey' => 'user_id'
)
);
Still no change
A few issues...
1) Your primary key for employees table should be id, not employee_id. Primary keys are always named id, according to cakephp conventions - http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html
2) Just as you've got a belongsTo in your Employee model, you should also add a hasOne relationship to your user model - see http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
3) In order to save a record, along with it's related data, the method you want is saveAll - check out the documentation here: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array

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);

yii not saving model

$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.

Categories