Codeigniter 3 validation rule - validation

i have a problem with form validation rule:
This is controller:
$this->load->library('form_validation');
$vL = array(
array(
"field" => $this->input->post('username'),
"rules" => "trim|required",
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
"field" => $this->input->post('password'),
"rules" => "trim|required",
'errors' => array(
'required' => 'You must provide a %s.',
),
)
);
$this->form_validation->set_rules($vL);
if ($this->form_validation->run()) {
print "ok";
} else {
print "not ok"<br /><br />";
}
View login:
echo form_open('', ['action' => '', 'id' => 'frmUsers', 'autocomplete' => 'off', 'class' => 'form-signin']);
echo form_input(['name' => 'username', 'class' => 'form-control', 'placeholder' => 'username', 'required' => 'required']);
echo form_input(['name' => 'password', 'class' => 'form-control', 'type' => 'password', 'required' => 'required']);
$data = array(
"type" => "submit",
"name" => "login",
"value" => "Sign in",
"class" => "btn btn-lg btn-primary btn-block",
);
echo form_submit($data);
I don't know where is the problem.Maybe because i don't have a label, but i'm not sure.Thank you !

in the form validation array the "field" is for the name of the input not for it's value so "field" => "username" and "field" => "password" etc.

Related

Send email in php using codeigniter

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.

Cake PHP 2.8.0 not validating

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.

Symfony forms entity/document sorting the property

I'm using the symfony forms for creating a select-box with all my users.
I display them by fullname, but want to sort them alphabetically.
$builder->add('transferTo', 'document', [
'class' => 'UserBundle:User',
'property' => 'fullname',
'label' => 'Overdragen aan',
'attr' => ['class' => 'form-control selectpicker'],
'label_attr' => ['class' => 'col-sm-2 control-label'],
'multiple' => false,
'required' => true
]);
How can i sort the users alphabetically on fullname of firstName?
What you need is to add queryBuilder to the form params
use Doctrine\ORM\EntityRepository;
$builder->add('transferTo', 'document', [
'class' => 'UserBundle:User',
'query_builder' => function(EntityRepository $repository) {
return $repository->createQueryBuilder('u')->orderBy('u.fullname', 'ASC');
}
'property' => 'fullname',
'label' => 'Overdragen aan',
'attr' => ['class' => 'form-control selectpicker'],
'label_attr' => ['class' => 'col-sm-2 control-label'],
'multiple' => false,
'required' => true
]);
I assumed the fieldname in your entity is u.fullname

CakePHPform checkbox validation error not shown, but input error

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.

Validation Errors not showing

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.

Resources