I am developing the simple register form.And develope the model,controller,view classes.but i am unable to show the error messages in my application.
User.php(Model class)
<?php
class User extends AppModel
{
var $name='User';
public $validate= array(
'username'=>array(
'rule'=>'notEmpty',
'required'=>true,
'message'=>'Enter your name'
),
'email' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your email'
)
);
}
?>
UsersController.php
<?php
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
array('action' => 'edit')
public function register() {
if ($this->User->validates()) {
$this->User->set($this->request->data);
$name = $this->request->data['User']['username'];
$email = $this->request->data['User']['email'];
}
else{
$this->flash('register fail');
}
}
}
?>
register.ctp
<?php
echo $this->Form->create('User',array('action'=>'register'));
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->end('Register');
?>
when i am click the register button above code is not showing the error messages.
Finally i got the answer to my question. i.e
User.php
<?php
class User extends AppModel
{
public $validate= array(
'username'=>array(
'rule'=>'notEmpty',
'required'=>false,
'message'=>'Enter your name'
),
'email' => array(
'rule' => 'notEmpty',
'required'=>false,
'message' => 'Please enter your email'
)
);
}
?>
UsersController.php
<?php
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
public function register() {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->redirect(array('controller'=>'users', 'action'=>'welcome'));
}
else{
echo"register fail";
}
}
public function welcome(){
$this->flash('register successfully','/users/register');
}
}
?>
register.ctp
<?php
echo $this->Form->create('User');
echo $this->Form->input('username',array('required'=>'false'));
echo $this->Form->input('email',array('required'=>'false'));
echo $this->Form->end('Register');
?>
this is the correct answer for above asking question.The main mistake done in my above question was i am given required'=>'true.',now given required'=>'false.' in register.ctp class.now problem resolved.
You need to change you register action in user controller like this:
public function register() {
$this->User->create();
if ($this->User->save($this->request->data)) { //this way it automatically save or show error message if there is one
$this->flash('register success');
}
else{
$this->flash('register fail');
}
}
Hope it helps.
Try this:
add a helper
var $helpers = 'session';
then add the flash message as
$this->Session->setFlash(__('error'));
What you actually want is to show the validation errors, so instead of
$this->flash('register fail');
Do
$this->Session->setflash($this->User->validationErrors);
$this->redirect('/users/register');
Related
Hi i need to add authentication to my staging website index page.Whenever the user tries to open the staging site it should show login page.Once user login then only he can see the website.I have tried added a code for displaying login page but it is displaying blank page not displaying any error messages as well.Here is my code.
As my website looks link will be for eg:staging.website.com
whenever the user tries to open this site it should ask login first.
Controller:
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('index_model');
$this->load->model('login_model');
}
public function index()
{
if($this->session->userdata('admin_logged_in'))
{
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records2'] = $this->index_model->get_all_banners();
$data['records7'] = $this->index_model->get_all_banners();
$data['mainpage'] = "index";
$this->load->view('templates/templatessss',$data);
}
else
{
$this->load->view('login');
}
}
public function login(){
$this->form_validation->set_rules('user_name','User Name','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
$this->form_validation->set_error_delimiters('<span class="ferror"> ','</span><br />');
if($this->form_validation->run()==FALSE){
$this->load->view('login');
}
else{
$user_name = $this->input->post('user_name');
$password = $this->input->post('password');
if($this->login_model->login_user($user_name,$password)):
redirect('welcome');
else:
$data['error'] = '<span class="ferror"> User Name or Password enter wrong. Please try again </span>';
$this->load->view('login',$data);
endif;
}
}
view(login.php):
<?php
$form_attributes = array('class'=>'admin_login_form', 'name'=>'admin_login_form', 'id'=>'admin_login_form', 'enctype' => "multipart/form-data");
$user_name = array('name' => 'user_name', 'id' => 'user_name', 'value' => set_value('user_name'),'class' =>'text');
$password = array('name' => 'password', 'id' => 'password','class' =>'text');
$submit = array('id' => 'login_details', 'value' => 'Login', 'name' => 'login_details');
?>
<?php echo form_open('welcome/login',$form_attributes);?>
<?php echo (validation_errors()) ? validation_errors() : ' ';?>
<?php echo (isset($error)) ? $error : '' ;?>
<?php echo form_label('User Name', $user_name['id']);?>
<?php echo form_input($user_name); if(!$this->input->post('user_name')) echo form_error('$user_name');?>
<?php echo form_label('Password', $password['id']);?>
<?php echo form_password($password);?>
<div class="sep"></div>
<button type="submit" class="ok"><?php echo form_submit($submit);?></button>
Model(login_model.php):
class login_model extends MY_Model
{
function login_user($user_name = '', $password=''){
$userdetails = array(
'user_name' => $user_name,
'password' => md5($password),
);
$this->db->where($userdetails);
$query = $this->db->get('login_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'user_id' => $user[0]->user_id,
'name' => $user[0]->name
);
$this->session->set_userdata('admin_logged_in', $sess_arry);
return true;
else:
return false;
endif;
}
}
Add this code in your Controller:
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('index_model');
$this->load->model('login_model');
}
public function index()
{
if($this->session->userdata('admin_logged_in'))
{
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records2'] = $this->index_model->get_all_banners();
$data['records7'] = $this->index_model->get_all_banners();
$data['mainpage'] = "index";
$this->load->view('templates/templatessss',$data);
}
else
{
redirect('welcome/login');
}
I hope it will work for you!!
Change your else condition
else
{
$this->load->view('login');
}
To
else
{
redirect('login');
}
welcome class
function __construct()
{
parent::__construct();
$this->load->helper("url");
if (!$this->session->userdata('admin_logged_in')){
redirect(base_url("login"));
}
$this->load->library('form_validation');
$this->load->model('index_model');
$this->load->model('login_model');
}
A login Class
class Login extends CI_Controller{
function index(){
if (isset($this->input->post())){
$this->form_validation->set_rules('user_name','User Name','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
$this->form_validation->set_error_delimiters('<span class="ferror"> ','</span><br />');
if($this->form_validation->run()==FALSE){
$this->load->view('login');
}
else{
$user_name = $this->input->post('user_name');
$password = $this->input->post('password');
if($this->login_model->login_user($user_name,$password)):
redirect('welcome');
else:
$data['error'] = '<span class="ferror"> User Name or Password enter wrong. Please try again </span>';
$this->load->view('login',$data);
endif;
}
}else{
$this->load->view("login");
}
}
this should working fine
Hi i'm quite new to yii framework, currently trying to establish a login through database authentication. but im repeatedly getting this error
CException
CActiveForm and its behaviors do not have a method or closure named
"getErrors".
can anybody help me out if this
Heres the Controller
<?php
class SiteController extends Controller
{
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function actionIndex()
{
$this->render('index');
}
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
$headers="From: $name <{$model->email}>\r\n".
"Reply-To: {$model->email}\r\n".
"MIME-Version: 1.0\r\n".
"Content-Type: text/plain; charset=UTF-8";
mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
public function actionLogin()
{
$form=new LoginForm;
if(isset($_POST['LoginForm']))
{
$form->attributes=$_POST['LoginForm'];
if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl);
}
$this->render('login',array('form'=>$form));
}
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
herers the model
<?php
class LoginForm extends CFormModel
{
public $email;
public $password;
private $_identity;
public function rules()
{
return array(
array('email, password', 'required'),
array('email', 'email'),
array('password', 'authenticate'),
);
}
public function attributeLabels()
{
return array('email'=>'Email Address');
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors()) // we only want to authenticate when no input errors
{
$identity=new UserIdentity($this->email,$this->password);
$identity->authenticate();
switch($identity->errorCode)
{
case UserIdentity::ERROR_NONE:
Yii::app()->user->login($identity);
break;
case UserIdentity::ERROR_USERNAME_INVALID:
$this->addError('email','Email address is incorrect.');
break;
default: // UserIdentity::ERROR_PASSWORD_INVALID
$this->addError('password','Password is incorrect.');
break;
}
}
}
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
}
else
return false;
}
}
here the view
<?php
/* #var $this SiteController */
/* #var $model LoginForm */
/* #var $form CActiveForm */
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div>
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($form); ?>
<div>
<?php echo CHtml::activeLabel($form,'email'); ?>
<?php echo CHtml::activeTextField($form,'email') ?>
</div>
<div>
<?php echo CHtml::activeLabel($form,'password'); ?>
<?php echo CHtml::activePasswordField($form,'password') ?>
</div>
<div>
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php echo CHtml::endForm(); ?>
endWidget(); ?>
it would be good if you include more of the error - e.g. on which line it occured and in which file, or at best the whole trace..
From what I read in your code it seems that you overwrite the $form variable, which actually hold your model.
In the SiteController you initialize the variable $form with the LoginForm model.
Then in the view you make this wrong call:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Therefore in all the CHtml calls you put a widget instead of a model variable to the functions
As you do not use the output of the widget in no specific way, it would be enough to remove the $form = $this->widget... and leave it only as $this->widget.. Or replace the variable for a new one.
<?php $myWidget = $this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
I'm trying to understand how Cakephp works. I built a connection system with a simple form (username and password). When I click on the submit button (with the correct username and password), I always receive the same flash message, "Your username or password was incorrect". I tried many things, but I don't know how to fix it .
If I'm logged, I want to be redirect on Google (it's the test i try) .
Look at my code :
login.ctp (View)
<?php
echo $this->Form->create('User',array('action'=>'login'));
echo $this->Form->inputs(array('legend'=>'Se connecter','username','password'));
echo $this->Form->end('Se connecter');
?>
UsersController
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow();
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->User->id = $this->Auth->user("id");
$this->redirect('http://www.google.fr');
} else {
$this->Session->setFlash('Your username or password was incorrect.');
}
}
}
}
User (Model)
<?php
App::uses('AppModel', 'Model', 'AuthComponent', 'Controller/Component');
class User extends AppModel {
public $actsAs = array('Acl' => array('type' => 'requester'));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['group_id'])) {
$groupId = $this->data['User']['group_id'];
} else {
$groupId = $this->field('group_id');
}
if (!$groupId) {
return null;
} else {
return array('Group' => array('id' => $groupId));
}
}
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
public $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
?>
The password in my table user (sql) :
password char(40) latin1_swedish_ci
I am creating login action in the yii framework, but I have an error and I cannot fix it. Here is the error:
Property "AdminIdentity.user_name" is not defined. `$record=Admin::model()->findByAttributes(array('username'=>$this->user_name));`
This is my login module:
login.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login_form',
'enableAjaxValidation'=>false,
'enableClientValidation' => true));
?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div id="lower">
<?php echo $form->Checkbox($model,'rememberMe'); ?>
<?php echo $form->labelEx($model,'rememberMe'); ?>
<input type="submit" value="Login"/>
</div>
<?php $this->endWidget(); ?>
AdminController and actionLogin
class AdminController extends Controller
{
public function actionLogin()
{
$this->layout = 'login';
$model=new LoginForm;
if(isset($_POST['ajax']) && $_POST['ajax']==='login_form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login()){
$this->redirect('/ktbeauty/index.php/categories/index');
}
}
$this->render('login',array(
'model'=>$model,
));
}
}
LoginForm
class LoginForm extends CFormModel{
public $username;
public $password;
public $rememberMe;
private $_identity;
public function rules()
{
return array(
// username and password are required
array('username, password', 'required','message'=>'input username requirement'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate','required','message'=>'input password requirement'),
);
}
public function attributeLabels()
{
return array(
'username'=>'User Name',
'rememberMe'=>'Remember me next time',
'password'=>'Password',
);
}
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new AdminIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
}
public function login()
{
if($this->_identity===null)
{
$this->_identity=new AdminIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->admin->login($this->_identity,$duration);
return true;
}
else
return false;
}
}
AdminIdentity class:
class AdminIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=Admin::model()->findByAttributes(array('username'=>$this->user_name));
var_dump($record);exit;
if($record===null)
{
$this->_id='user Null';
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($record->password!==$this->password)
{
$this->_id=$this->user_name;
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else if($record['user_active']!=='1')
{
$err = "You have been Inactive by Admin.";
$this->errorCode = $err;
}
else
{
$this->_id=$record['ad_id'];
$this->setState('user_name', $record['user_name']);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
Admin Model class:
class Admin extends CActiveRecord
{
public function tableName()
{
return 'admin';
}
public function rules()
{
return array(
array('user_status','length', 'max'=>1),
array('user_active','length', 'max'=>1),
array('user_name, password, email', 'length', 'max'=>100),
array('phone, cellphone, name', 'length', 'max'=>45),
array('ad_id, user_name, password, email, phone, cellphone, name, user_status, user_active', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array(
);
}
public function attributeLabels()
{
return array(
'ad_id' => 'Ad',
'user_name' => 'User Name',
'password' => 'Password',
'email' => 'Email',
'phone' => 'Phone',
'cellphone' => 'Cellphone',
'name' => 'Name',
'user_status' => 'User Status',
'user_active' => 'User Active',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('ad_id',$this->ad_id);
$criteria->compare('user_name',$this->user_name,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('email',$this->email,true);
$criteria->compare('phone',$this->phone,true);
$criteria->compare('cellphone',$this->cellphone,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('user_status',$this->user_status);
$criteria->compare('user_active',$this->user_active);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
class AdminIdentity extends CUserIdentity and in CUserIdentity there are 2 properties defined:
$username
$password
So you should either change
$record=Admin::model()->findByAttributes(array('username'=>$this->user_name));
to
$record=Admin::model()->findByAttributes(array('username'=>$this->username));
or
declare $user_name in your AdminIdentity class. If you choose to declare the new property make sure you set a value in the constructor (more changes will be needed)
I have this code but the flash message is displayed incorrectly.
I want to display the message in:
http://xxx/cake/ ----(add action)
but actually the message is shown in:
http://xxx/cake/users/ ----(index action)
How can i solve this? I don't have any view to activation. I just want redirect to the add action and display the flash message after that.
class UsersController extends AppController {
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function add() {
}
public function activation() {
$email = $this->request->query['email'];
$codeLink = $this->request->query['code'];
if($this->User->activationAccount($email, $codeLink)) {
$this->Session->setFlash(__('Success'));///should be shown in add
$this->redirect(array('action' => 'add'));
}
else {
$this->Session->setFlash(__('Error.'));//should be shown in add
$this->redirect(array('action' => 'add'));
}
}
}
routes.php
Router::connect('/', array('controller' => 'users', 'action' => 'add'));
Just destroy this session:
array
'fb_400xxxxxxx96_state' => string 'ce3xxasdxxxxxxasdasdxxxxxxxf' (length=32)
public function add() {
$this->Session->destroy();
//some code
}
may be you should have a look at this tuto which cover this