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'),
);
}
Related
First of all, this post is going to be long, thanks for helping tho.
Hello so I've been trying to create a login and register system on my CodeIgniter Application. So far it works great, I can create and fetch them(if not logged in) wherever I want them to be displayed, the problem that now comes to me is the restricting part.
For example I have an admin_controller to which I need to restrict the access. Rather than adding a code to any controller that needs the same configuration, I created a "MY_Controller" in the core folder, here is my code:
<?php
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
}
}
class Admin_Controller extends MY_Controller{
function __construct(){
parent::__construct();
// Check Login
/*if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}*/
}
}
class Public_Controller extends MY_Controller{
public function __construct(){
parent::__construct();
$this->load->library('menu');
$pages_public /*$this->pages*/ = $this->menu->get_pages();
// Brand/Logo
$this->brand = 'My Website';
// Banner
$this->banner_heading = 'Welcome To Our Website';
$this->banner_text = 'This example is a quick exercise to illustrate how the default, static navbar and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.';
$this->banner_link = 'pages/show/our-team';
}
}
and this is what I have on my admin_controller, so far nothing wrong:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends Admin_Controller {
public function index(){
$data['pages'] = $this->Page_model->get_list();
// Load template
$this->template->load('admin', 'default', 'pages/index', $data);
}
public function add(){
// Field Rules
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
$this->form_validation->set_rules('subject_id', 'Subject', 'trim|required');
$this->form_validation->set_rules('body', 'Body', 'trim|required');
$this->form_validation->set_rules('is_published', 'Publish', 'required');
$this->form_validation->set_rules('is_featured', 'Feature', 'required');
$this->form_validation->set_rules('order', 'Order', 'integer');
if($this->form_validation->run() == FALSE){
$subject_options = array();
$subject_options[0] = 'Select Page Category';
$subject_list = $this->Pages_categories_model->get_list();
foreach($subject_list as $subject){
$subject_options[$subject->id] = $subject->name;
}
$data['subject_options'] = $subject_options;
// Load template
$this->template->load('admin', 'default', 'pages/add', $data);
} else {
$slug = str_replace(' ', '-', $this->input->post('title'));
$slug = strtolower($slug);
// Page Data
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'subject_id' => $this->input->post('subject_id'),
'body' => $this->input->post('body'),
'is_published' => $this->input->post('is_published'),
'is_featured' => $this->input->post('is_featured'),
'in_menu' => $this->input->post('in_menu'),
'user_id' => $this->session->userdata('user_id'),
'order' => $this->input->post('order')
);
// Insert Page
$this->Page_model->add($data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'added',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A new page was added ('.$data["title"].')'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been added');
// Redirect
redirect('admin/pages');
}
}
public function edit($id){
// Field Rules
$this->form_validation->set_rules('title', 'Title', 'trim|required|min_length[3]');
$this->form_validation->set_rules('subject_id', 'Subject', 'trim|required');
$this->form_validation->set_rules('body', 'Body', 'trim|required');
$this->form_validation->set_rules('is_published', 'Publish', 'required');
$this->form_validation->set_rules('is_featured', 'Feature', 'required');
$this->form_validation->set_rules('order', 'Order', 'integer');
if($this->form_validation->run() == FALSE){
$data['item'] = $this->Page_model->get($id);
$subject_options = array();
$subject_options[0] = 'Select Page Category';
$subject_list = $this->Pages_categories_model->get_list();
foreach($this->Pages_categories_model->get_list() as $subject){
$subject_options[$subject->id] = $subject->name;
}
$data['subject_options'] = $subject_options;
// Load template
$this->template->load('admin', 'default', 'pages/edit', $data);
} else {
$slug = str_replace(' ', '-', $this->input->post('title'));
$slug = strtolower($slug);
// Page Data
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'subject_id' => $this->input->post('subject_id'),
'body' => $this->input->post('body'),
'is_published' => $this->input->post('is_published'),
'is_featured' => $this->input->post('is_featured'),
'in_menu' => $this->input->post('in_menu'),
'user_id' => $this->session->userdata('user_id'),
'order' => $this->input->post('order')
);
// Update Page
$this->Page_model->update($id, $data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'updated',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A page was updated ('.$data["title"].')'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been updated');
// Redirect
redirect('admin/pages');
}
}
public function delete($id){
$title = $this->Page_model->get($id)->title;
// Delete Page
$this->Page_model->delete($id);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'page',
'action' => 'deleted',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A page was deleted'
);
// Insert Activity
$this->Activity_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Page has been deleted');
// Redirect
redirect('admin/pages');
}
}
the problem comes from the controller users_controller. I already created an account with some data and that data should at least allow me to have access to the admin_controller which it does not, instead it redirects me to the admin/login form.
I would like to say that for some reason when I tried to add a page, I get an error message saying that user_id cannot be null, but as I'm "supposed" to be logged in that error should not appear. Any knows how to fix it?
Error Message
Error Number: 1048 Column 'user_id' cannot be null INSERT INTO 'pages'
('title', 'slug', 'subject_id', 'body', 'is_published', 'is_featured',
'in_menu', 'user_id', 'order') VALUES ('Page One', 'page-one', '1', '
thrhjtyjrjrj ', '1', '0', '1', NULL, '1')
Filename:
C:/xampp/htdocs/codeigniter/application/models/page_model.php Line
Number: 20
User_Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$data['users'] = $this->User_model->get_list();
// Load template
$this->template->load('admin', 'default', 'users/index', $data);
}
public function add(){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|matches[password2]');
$this->form_validation->set_rules('password2','Confirm Password','trim|required|min_length[6]|matches[password2]');
if ($this->form_validation->run() == FALSE){
// Load View Into Template
$this->template->load('admin','default','users/add');
} else {
// Create Page Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password'))
);
// Add User
$this->User_model->add($data);
//Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'added',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A new user was added ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been added');
// Redirect to pages
redirect('admin/users');
}
}
public function edit($id){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
if ($this->form_validation->run() == FALSE){
// Get Current Subject
$data['item'] = $this->User_model->get($id);
//Load View Into Template
$this->template->load('admin','default','users/edit', $data);
} else {
// Create User Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username')
);
// Update User
$this->User_model->update($id, $data);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'updated',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A user was updated ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
//Create Message
$this->session->set_flashdata('success', 'User has been updated');
//Redirect to Users
redirect('admin/users');
}
}
public function delete($id){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
// Get Username
$username = $this->User_model->get($id)->username;
// Delete User
$this->User_model->delete($id);
// Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'deleted',
'user_id' => $this->session->userdata('user_id'),
'message' => 'A user was deleted'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been deleted');
// Redirect to Subjects
redirect('admin/users');
}
public function login(){
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//Load View Into Template
$this->template->load('admin','login','users/login');
} else {
// Get Post Data
$username = $this->input->post('username');
$password = $this->input->post('password');
$enc_password = md5($password);
$user_id = $this->User_model->login($username, $enc_password);
if($user_id){
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => true
);
// Set Session Data
$this->session->set_userdata($user_data);
// Create Message
$this->session->set_flashdata('success', 'You are logged in');
// Redirect to pages
redirect('admin');
} else {
// Create Error
$this->session->set_flashdata('error', 'Invalid Login');
// Redirect to pages
redirect('admin/users/login');
}
}
}
public function register(){
$this->form_validation->set_rules('first_name','First Name','trim|required|min_length[2]');
$this->form_validation->set_rules('last_name','Last Name','trim|required|min_length[2]');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]');
$this->form_validation->set_rules('email','Email','trim|required|min_length[7]|valid_email');
$this->form_validation->set_rules('password','Password','trim|required|min_length[4]|matches[password2]');
$this->form_validation->set_rules('password2','Confirm Password','trim|required|min_length[6]|matches[password2]');
if ($this->form_validation->run() == FALSE){
// Load View Into Template
$this->template->load('admin','login','users/register');
} else {
// Create Page Data Array
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password'))
);
// Add User
$this->User_model->add($data);
//Activity Array
$data = array(
'resource_id' => $this->db->insert_id(),
'type' => 'user',
'action' => 'registered',
'user_id' => $this->session->userdata('username'),
'message' => 'A new user was registered ('.$data["username"].')'
);
// Add Activity
$this->Activity_model->add($data);
// Create Message
$this->session->set_flashdata('success', 'User has been registered');
// Redirect to pages
redirect('admin/users/login');
}
}
public function logout(){
$this->session->unset_userdata('logged_in');
$this->session->unset_userdata('user_id');
$this->session->unset_userdata('username');
$this->session->sess_destroy();
// Message
$this->session->set_flashdata('success', 'You are logged out');
redirect(base_url());
}
}
Here is my user_model(in case you would like to check it):
<?php
class User_model extends CI_MODEL{
function __construct(){
parent::__construct();
$this->table = 'users';
}
public function get_list(){
$query = $this->db->get($this->table);
return $query->result();
}
public function get($id){
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row();
}
public function add($data){
$this->db->insert($this->table, $data);
}
public function update($id, $data){
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
public function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->table);
}
public function login($username, $password){
$this->db->select('*');
$this->db->from($this->table);
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->row()->id;
} else {
return false;
}
}
}
1/ You should write a private method for checking logged user like this
private function checkLogin()
{
if(!$this->session->userdata('logged_in')){
redirect('admin/login');
}
}
2/ You must make sure that you loaded the library session.
I have to implement the validation as mentioned in the title that either one of the two fields (email, phone) is required. I am doing this in my model:
[['email'],'either', ['other' => ['phone']]],
And this is the method:
public function either($attribute_name, $params) {
$field1 = $this->getAttributeLabel($attribute_name);
$field2 = $this->getAttributeLabel($params['other']);
if (empty($this->$attribute_name) && empty($this->$params['other'])) {
$this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
return false;
}
return true;
}
When I access my index page, it gives me this error:
Exception (Unknown Property) 'yii\base\UnknownPropertyException' with
message 'Setting unknown property: yii\validators\InlineValidator::0'
Any help?
If you don't care that both fields show an error when the user provides neither of both fields:
This solutions is shorter than the other answers and does not require a new validator type/class:
$rules = [
['email', 'required', 'when' => function($model) { return empty($model->phone); }],
['phone', 'required', 'when' => function($model) { return empty($model->email); }],
];
If you want to have a customized error message, just set the message option:
$rules = [
[
'email', 'required',
'message' => 'Either email or phone is required.',
'when' => function($model) { return empty($model->phone); }
],
[
'phone', 'required',
'message' => 'Either email or phone is required.',
'when' => function($model) { return empty($model->email); }
],
];
The rule should be:
['email', 'either', 'params' => ['other' => 'phone']],
And method:
public function either($attribute_name, $params)
{
$field1 = $this->getAttributeLabel($attribute_name);
$field2 = $this->getAttributeLabel($params['other']);
if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
$this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
}
}
Improved variant
['gipsy_team_name', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => 'poker_strategy_nick_name']],
['vkontakte', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => ['odnoklasniki','odnoklasniki']]],
Added 'skipOnEmpty'=>false for forcing validating and 'other' can be array
/**
* validation rule
* #param string $attribute_name
* #param array $params
*/
public function either($attribute_name, $params)
{
/**
* validate actula attribute
*/
if(!empty($this->$attribute_name)){
return;
}
if(!is_array($params['other'])){
$params['other'] = [$params['other']];
}
/**
* validate other attributes
*/
foreach($params['other'] as $field){
if(!empty($this->$field)){
return;
}
}
/**
* get attributes labels
*/
$fieldsLabels = [$this->getAttributeLabel($attribute_name)];
foreach($params['other'] as $field){
$fieldsLabels[] = $this->getAttributeLabel($field);
}
$this->addError($attribute_name, \Yii::t('poker_reg', 'One of fields "{fieldList}" is required.',[
'fieldList' => implode('"", "', $fieldsLabels),
]));
}
I am working with ajax crud in Yii. I have a radiobuttonlist in the form. I get 'cannot be blank' error even if it is selected. Please help me find the problem.
In the ajax_form the code is:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'universal-electives-form',
// 'htmlOptions' => array('enctype' => 'multipart/form-data'),
'action' => $actionUrl,
// 'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'focus'=>array($model,'name'),
'errorMessageCssClass' => 'input-notification-error error-simple png_bg',
'clientOptions'=>array('validateOnSubmit'=>true,
'validateOnType'=>false,
'afterValidate'=>'js_afterValidate',
'errorCssClass' => 'err',
'successCssClass' => 'suc',
'afterValidate' => 'js:function(form,data,hasError){ $.js_afterValidate(form,data,hasError); }',
'errorCssClass' => 'err',
'successCssClass' => 'suc',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError){
$.js_afterValidateAttribute(form, attribute, data, hasError);
}'
),
));
<?php echo $form->labelEx($model,'offered_for',array('style'=>'color:#000000')); ?>
<?php echo $form->radioButtonList($model,'offered_for',array('1'=>'Boys','2'=>'Girls','0'=>'Both')); ?>
<?php echo $form->error($model,'offered_for'); ?>
In the model, the rules are:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, desc, batch, offered_for, created_by, created_at', 'required'),
array('offered_for, created_by', 'numerical', 'integerOnly'=>true),
array('name, desc, batch', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, name, desc, batch, offered_for, created_by, created_at', 'safe', 'on'=>'search'),
);
}
In the controller:
public function actionAjax_Create(){
if(isset($_POST['UniversalElectives']))
{
$model=new UniversalElectives;
$batch_ids = '';
$count = count($_POST['UniversalElectives']['batch']);
//set the submitted values
$model->attributes=$_POST['UniversalElectives'];
$model->offered_for = $POST['UniversalElectives']['offered_for'];
for($i=0;$i<=$count;$i++)
{
if($i!=0 and $i!=$count){
$batch_ids = $batch_ids.',';
}
$batch_ids = $batch_ids.$_POST['UniversalElectives']['batch'][$i];
}
$model->batch = $batch_ids;
$model->created_by = Yii::app()->user->id;
$model->created_at = date('Y-m-d h:i:s');
//return the JSON result to provide feedback.
if($model->save(false)){
echo json_encode(array('success'=>true,'id'=>$model->primaryKey) );
exit;
} else
{
echo json_encode(array('success'=>false));
exit;
}
}
}
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.
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.