I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.
Related
ok so here i'm looking for some help. i have a contact us form of a website. It has three fields name, email and message. What i need to do is when user fills the form email should be send on admin email which display message of the user and its email and name too. I have a code which is working fine it gives me the message of email sent but when i open mail there is no email. Kindly i need your help. Here is the code
<h3 class="title-big wow fadeIn">Contact Us</h3>
<br>
</div>
<div class="col-md-12 text-center">
<?php if($success != ""): ?>
<span class="col-md-4 col-md-offset-4" style="color:#D91E18"> <?php echo $success;?></span>
<?php endif; ?>
<div class="form-group col-md-offset-4 col-md-4 col-md-offset-4 wow fadeInDown">
<form name="myform" role="form" action="sendmail" method="post">
<div class="form-group">
<?php echo form_input($first_name);?>
</div>
<div class="form-group">
<?php echo form_input($email);?>
</div>
<div class="form-group">
<?php echo form_textarea($message1);?>
<br>
<a class="sign-up-button btn btn-border btn-lg col-md-offset-3 col-md-6 col-md-offset-3 wow fadeInUp" data-wow-delay="1s" href="javascript: submitform()">Submit Query</a>
</div>
</form>
controller.php
public function contact()
{
$data['success'] = (validation_errors() ? validation_errors() : ($this->session->flashdata('message')));
//$data['message'] = (validation_errors() ? validation_errors() : ($this->session->flashdata('message')));
$data['message1'] = array(
'name' => 'message1',
'id' => 'message1',
'class' => 'form-control',
'placeholder' => "Enter message here...",
'size' => 32,
'maxlength' => 500,
'rows' => 5,
'cols' => 41,
);
$data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "First Name...",
'size' => 32,
'maxlength' => 50,
);
$data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "Email Address (Mandatory)",
'size' => 32,
'maxlength' => 128,
);
$this->load->view('contact',$data);
}
public function sendmail()
{
$this->form_validation->set_rules('first_name', 'Name', 'required');
//$this->form_validation->set_rules('last_name', 'Name', 'required');
$this->form_validation->set_rules('message1', 'Message', 'required');
$this->form_validation->set_rules('email', 'Email Address', 'required');
//$this->form_validation->set_rules('email_confirm', 'Reenter Email Address', 'required');
if ($this->form_validation->run() == true)
{
$data = array(
'first_name' => $this->input->post('first_name'),
//'last_name' => $this->input->post('last_name'),
'message1' => $this->input->post('message1'),
'email' => $this->input->post('email'),
);
//if ($this->form_validation->run() == true)
//{
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'auth' => true,
'smtp_user' => '********#gmail.com',
'smtp_pass' => '********'
);
$emailsubject = $data['first_name']." ".$data['last_name']." has sent a Query message.";
$this->load->library('email',$config);
$this->email->set_newline("\r\n");
// $this->email->initialize($config);
$this->email->from('********#gmail.com', 'AOTS Lahore Regional Center');
//$this->email->to('********#gmail.com');
$this->email->to('********#gmail.com');
$this->email->cc('********#gmail.com');
$this->email->subject($emailsubject);
$this->email->message($data['message1']."\nEmail ID: ".$data['email']);
if ($this->email->send())
{
$data['success'] = "Your Query has been sent successfully... !!";
//$data['message'] = (validation_errors() ? validation_errors() : ($this->session->flashdata('message')));
$data['message1'] = array(
'name' => 'message1',
'id' => 'message1',
'class' => 'form-control',
'placeholder' => "Enter message here...",
'size' => 32,
'maxlength' => 500,
'rows' => 5,
'cols' => 41,
);
$data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "First Name...",
'size' => 32,
'maxlength' => 50,
);
$data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "Email Address (Mandatory)",
'size' => 32,
'maxlength' => 128,
);
$this->load->view('contact',$data);
}
else
{
$data['success'] = show_error( $this->email->print_debugger());
}
}
//}
else
{
$data['success'] = (validation_errors() ? validation_errors() : ($this->session->flashdata('message')));
$data['message1'] = array(
'name' => 'message1',
'id' => 'message1',
'class' => 'form-control',
'placeholder' => "Enter message here...",
'size' => 32,
'maxlength' => 500,
'rows' => 5,
'cols' => 41,
);
$data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "First Name...",
'size' => 32,
'maxlength' => 50,
);
$data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'class' => 'form-control',
'placeholder' => "Email Address (Mandatory)",
'size' => 32,
'maxlength' => 128,
);
$this->load->view('contact',$data);
}
}
********#gmail.com is the email where mail should be send
You need to use :
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '********#gmail.com',
'smtp_pass' => '********',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
In order to send an email from (say) youremailid#gmail.com to an email id *****#gmail.com follow the steps below:
step 1) the config array as below
$config = array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'auth' => true,
'smtp_user' => 'youremailid*****#gmail.com', // email id of sender in this case 'youremailid#gmail.com' is the sender
'smtp_pass' => 'passwordofyouremailid', // password of sender gmail id ie. password of 'youremailid#gmail.com'
'newline' => "\r\n",
);
step 2) Load the email library and call initialize
$this->load->library('email',$config);
$this->email->initialize($config);
step 3) After setting subjects and other info into variables do the following
$this->email->from('youremailid****#gmail.com', 'Sender Name'); // sender emailid and name in this case `youremailid#gmail.com` is sending email
$this->email->to('*****#gmail.com'); // receiver email id in this case '*****#gmail.com' is to whome you want to send . so *****#gmail.com is the email id
$this->email->cc('*****#gmail.com'); // same as above if you want cc to include
$this->email->subject($emailsubject); // subject of email
if ($this->email->send())
{
// rest of your code
}
remember there youremailid#gmail.com is the sender and *****#gmail.com is the receiver.
I wanted to fetch the selected value from the database and display it in codeigniter form_dropdown() function but it displays wrong.
Controller:
$type = array(
'options' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
'attributes' => array(
'class' => 'form-control'
)
);
View:
<?php echo form_dropdown('type', $type['options'],'', $type['attributes']) ?>
The Screenshot
Try the below code:
Controller:
$this->data['type'] = array(
'name' => 'type_value',
'attributes' => 'class="form-control"',
'value' => (isset($database_type_value) && trim($database_type_value)) ? $database_type_value: $this->input->post('type_value',TRUE), //$database_type_value - value from database
'options_list' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
);
View:
<?php echo form_dropdown($type['name'],$type['options_list'],$type['value'],$type['attributes']);?>
I have the folowing validate inside my Workshops class
public $validate = array(
'programa'=> array(
'allowEmpty' => false,
'required' => true
),
'lugar'=> array(
'allowEmpty' => false,
'required' => true
),
'fecha_inicio'=> array(
'allowEmpty' => false,
'required' => true
),
'fecha_fin'=> array(
'allowEmpty' => false,
'required' => true
),
'objetivo'=> array(
'allowEmpty' => false,
'required' => true
),
'instructor'=> array(
'allowEmpty' => false,
'required' => true
)
);
however when I save with empty fields a record is created in the database, the validation is not being done.
This is the code for my add form
<h1>Agregar Taller</h1>
<?php
echo $this->Form->create('Workshop');
echo $this->Form->input('nombre');
echo $this->Form->input('fecha_inicio',
array(
'label' => 'Fecha Inicio',
'dateFormat' => 'DMYhm',
'minYear' => date('Y') - 0,
'maxYear' => date('Y') + 2,
));
echo $this->Form->input('fecha_fin',
array(
'label' => 'Fecha fin',
'dateFormat' => 'DMYhm',
'minYear' => date('Y') - 0,
'maxYear' => date('Y') + 2,
));
echo $this->Form->input('caracteristica_tec21');
echo $this->Form->input('programa');
echo $this->Form->input('lugar');
echo $this->Form->input('instructor');
echo $this->Form->input('objetivo', array('rows' => '3'));
echo $this->Form->end('Guardar Taller');
?>
And here is my controller
<?php
class WorkshopsController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this->set('workshops',$this->Workshop->find('all'));
}
public function view($id = null){
if(!$id){
throw new NotFoundException(__('Taller inválido'));
}
$workshop = $this->Workshop->findById($id);
if (!$workshop) {
throw new NotFoundException(__('Taller inválido'));
}
$this->set('workshop', $workshop);
}
public function add() {
if ($this->request->is('post')) {
$this->Workshop->create();
if ($this->Workshop->save($this->request->data)) {
$this->Flash->success(__('El taller se ha agregado'));
return $this->redirect(array('action' => 'index'));
}else{
$this->Flash->error(__('No se ha podido agregar el taller'));
}
}
}
}
?>
You suppose to add a message field in every form field's validation, this is the message which shown in view file. Please see the below:
public $validate = array(
'programa' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the programa."
),
'lugar' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the lugar."
),
'fecha_inicio' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the fecha_inicio."
),
'fecha_fin' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the fecha_fin."
),
'objetivo' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the objetivo."
),
'instructor' => array(
'allowEmpty' => false,
'required' => true,
'message' => "Please Enter the instructor."
)
);
If the answer is correct, Please don't forget to mark it as a answer.
I have a form with required fields, one field is a checkbox. All validation errors will be shown, but no error from checkbox field. I installed DebugKit-Plugin and see, that there will be a validation error, but the message wouldn't shown.
class Users extends AppModel {
public $name = 'Users';
public $validate = array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Bitte geben Sie ihre Email-Adresse ein',
'allowEmpty' => false,
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Diese Adresse ist bereits angemeldet',
),
'email' => array(
'rule' => array('email',true),
'message' => 'Bitte geben Sie eine gültige Email-Adresse ein',
'allowEmpty' => false,
),
),
'terms' => array(
'rule' => array('comparison','!=',0),
'message' => 'Sie müssen unseren Nutzungsbedingungen zustimmen',
'allowEmpty' => false,
),
);
}
Form:
<div class="right text-right" id="register_form">
<?php
echo $this->Form->create('Users', array('action' => 'register', 'inputDefaults' => array()));
echo $this->Form->input('gender', array('label' => 'Anrede: ', 'class' => 'inputField', 'options' => array('m' => 'Herr', 'f' => 'Frau')));
echo $this->Form->input('first_name', array('label' => 'Vorname: ', 'class' => 'inputField'));
echo $this->Form->input('last_name', array('label' => 'Nachname: ', 'class' => 'inputField'));
echo $this->Form->input('email', array('label' => 'Email: ', 'class' => 'inputField'));
echo $this->Form->input('terms', array('div' => true, 'type' => 'checkbox', 'value' => 0, 'label' => false, 'before' => ' <label for="UsersTerms">Ich akzeptiere die '.$this->Html->link('AGB', array('controller' => 'pages', 'action' => 'terms')).' </label>'));
echo $this->Form->submit('Anmelden', array('class' => 'button'));
echo $this->Form->end();
?>
</div>
Controller:
public function register() {
if ($this->Auth->user())
$this->redirect($this->referer('/'));
if ($this->request->is("post")) {
$this->Users->create();
$this->Users->set(Sanitize::clean($this->request->data));
#if ($this->Users->validates())
# die(debug($this->Users->validationErrors));
$this->_hash = $this->Auth->password($this->Users->data['Users']['email']);
$this->_password = $this->__randomString(8, 8);
$this->Users->set('password', $this->Auth->password($this->_password));
if ($this->Users->save()) {
$this->Users->id = $this->Users->getLastInsertID();
$this->_sendActivationMail();
$this->Session->setFlash('An die angegebene Emailadresse wurde soeben ein Aktivierungslink versendet.', 'default', array('class' => 'yellow'));
$this->redirect($this->referer());
} else {
$this->Session->setFlash('Ein Fehler ist aufgetreten', 'default', array('class' => 'red'));
}
}
}
I tried with a "$this->Form->error('terms');" but when I debug this line, in case of error there will be only
<div class="error_message"></div>
CakePHP is last version. Searching since 4 hours for help, but google has no answer. Have you?
Greetings
M.
If anyone has same problem, i could solve mine:
Problem was special char "ü". I tried to save my file with ISO 8859-1 but it needed to save with UTF8. Now error message will be shown.
Iam new in cakephp ,I need to validate a form.
This is the code:
Controller:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
public function index(){
}
function add_task()
{
if(!empty($this->data)) {
//print_r($this->data);
$this->Task->set($this->data);
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
// didn't validate logic
echo $errors = $this->Task->validationErrors;
}
}
}
}
?>
Model:
<?php
class Task extends AppModel
{
public var $name = 'Task';
var $useDbConfig = 'travanco_erp';
public var $useTable = 'tbl_tasks'; // This model uses a database table 'exmp'
public var $validate = array(
'task_title_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The title field is required'
),
'task_description_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The description field is required'
),
'task_from_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The from date field is required'
),
'task_to_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The to date field is required'
)
);
}
?>
This is the view:
<div class="employeeForm" style="width:64%; padding:10px 30%;">
<?php echo $this->Form->create('test', array('class'=>'form'));?>
<fieldset style="width:36em; padding:0px 0px;">
<div style="width:475px; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#333333; font-weight:bold; margin-left:20px; margin-top:10px;">Add Task</div>
<br/>
<?php
/*echo $this->Form->input('task_ids_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Task ID',
));*/
echo $this->Form->input('task_title_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Title',
));
echo $this->Form->input('task_description_mm', array( 'type' => 'textarea',
'cols'=>60,
'rows' => 5,
'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Description',
));
echo $this->Form->input('task_from_mm', array( 'div'=>'frm_filed_new','id'=>'task_from_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'From',
));
echo $this->Form->input('task_to_mm', array( 'div'=>'frm_filed_new','id'=>'task_to_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'To',
));
?>
<br/>
<?php echo $this->Form->button('Submit', array('type'=>'submit','escape'=>true)); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
The validation not working.
What is the error in my code?
How can i solve this?
EDIT:
It is the mistake of misconfiguration of databse.php file.Now its corrected .And the print_r($errors) displays the errors.But that not displayed in the view page , i mean near the textboxes.
This is that error array:
Array ( [task_title_mm] => Array ( [0] => The title field is required ) [task_description_mm] => Array ( [0] => The description field is required ) [task_from_mm] => Array ( [0] => The from date field is required ) [task_to_mm] => Array ( [0] => The to date field is required ) )
How can i put it in near the text box?
CakePHP is designed to automatically validate model and display validation errors. Auto validation runs on model save. In your case:
$this->Task->save($this->request->data);
above will trigger validation. There is no need to run: $this->Task->validates() - If you do so, you also have to take care of displaying validation error by your own. So I think you simply should try:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
function add_task()
{
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Task->save($this->request->data)) {
//saved and validated
}
}
}
}
?>
one thing i noticed in your code that you are writing in your model
public var $validate=array();
instead try
public $validate= array() or var $validate=array();
Validation should work after words.
Thanks :)
Try this:
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
$this->validateErrors($this->Task);
$this->render();
}