<? if ( ! defined('BASEPATH')) exit();
class Registration extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('registration_model');
}
public function index() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email|callback_email_available');
if($this->form_validation->run() == FALSE) {
$this->load->view('registration');
} else {
$this->registration_model->add_user();
}
}
# Check E-mail
public function email_available($email) {
$this->db->select('email');
$this->db->where('email', $email);
$query = $this->db->get('users');
$result = $query->row();
if(!empty($result)) {
$this->form_validation->set_message('email_available', 'This e-mail belongs to another user.');
return FALSE;
} else {
return TRUE;
}
}
}
?>
I have a registration form with Form Validation.
And I have a callback function to validate email uniqueness.
All code works fine, but I can directly access to callback function with errors
examle.com/registration/email_available
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Registration::email_available()
Filename: controllers/registration.php
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: email
Filename: controllers/registration.php
How can I deny direct access to callback function?
You can prefix the method name with an _ to deny access through HTTP request.
My suggestion is to tuck your validation rules into a separate file. CodeIgniter supports this by allowing you to save validation configurations in config/form_validation.php. Take a look at the Form Validation Documentation, specifically the section labelled Saving Sets of Validation Rules to a Config File.
Your controller's index:
public function index() {
$this->load->library('form_validation');
if($this->form_validation->run('submit_registration') == FALSE) {
$this->load->view('registration');
}
else{
$this->registration_model->add_user();
}
}
config/form_validation.php
$config = array
(
'submit_registration' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|email_available'
),
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|alpha_numeric|etc'
)
),
'some_other_submission' => array(
array(
'field' => 'somefield',
'label' => 'SomeField',
'rules' => 'some|rules'
),
array(
'field' => 'getit',
'label' => 'Get The Point?',
'rules' => 'trim'
)
)
);
libraries/MY_Form_validation.php
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array()){
parent::__construct($config);
}
function email_available($email){
$CI =& get_instance();
//check your database with the $CI variable...
if(email_exists) return TRUE;
else return FALSE;
}
}
Related
I am trying to retrieve user information through api in CS-cart. But it returns only limited information. How can we modify the code to get all the user info for ex- user profiles, address, gst and all.
you can create your own API.
/var/www/html/app/addons/addon_name/Tygh/Api/Entities/Egg.php
<?php
namespace Tygh\Api\Entities;
use Tygh\Api\AEntity;
use Tygh\Api\Response;
class Egg extends AEntity
{
public function index($id = '', $params = array())
{
if(empty($id))
{
$dd=db_get_array("SELECT * FROM ?:table_name");
//result all rows
}
else
{
// for filtering purpose
$where=array("id"=>$id);
$dd=db_get_array("SELECT * FROM ?:table_name where ?w",$where);
//result-> specific one row
}
return array(
'status' => Response::STATUS_OK,
'data' => $dd
);
}
public function create($params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function update($id, $params)
{
return array(
'status' => Response::STATUS_OK,
'data' => array()
);
}
public function delete($id)
{
return array(
'status' => Response::STATUS_NO_CONTENT,
);
}
public function privileges()
{
return array(
'index' => true,
'create' => 'create_things',
'update' => 'edit_things',
'delete' => 'delete_things',
'index' => 'view_things'
);
}
public function privilegesCustomer()
{
return array(
'index' => true
);
}
}
?>
Remarks:
file name,
class name,
file path
Or you can edit the user API entity from this location.
app/Tygh/Api/Entities/Users.php
Any doubts , then kick me in...
Config/login_rules.php
Here for the callback function check_email_existence
I want to pass three parameters which are (email,table, field)
<?php
/**
* SETTING VALIDATION RULES FOR THE LOGIN FORM
*/
$config['login_settings'] = array(
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|min_length[6]|max_length[20]|xss_clean',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email|xss_clean|check_email_existence'
)
);
?>
I have extended the form validation helper libraries/MY_Form_validation.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
protected $CI;
public function __construct($config = array())
{
parent::__construct($config);
$this->CI =& get_instance();
}
function check_email_existence($email,$table,$field) {
$this->CI->form_validation->set_message('check_email_existence', 'This %s id is not registered.');
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $field = '".$email."' ");
$row = $query->row();
return ($row->count > 0) ? 'success' : 'failure';
}
}//class
?>
A callback function accepts two parameters: ($postdata, $param).
$param receives whatever you define as the rule's parameter via [...] after the rule's name:
'rules' => 'required|trim|valid_email|xss_clean|check_email_existence[table,field]'
function check_email_existence($email, $param) {
// extract table and field from $param
...
I have started to create a controller called User in codeigniter
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array( 'encrypt', 'form_validation' ));
}
public function index()
{
}
/*
* Create loginform
* Parameters: void
* Return: html of loginform;
*/
public static function loginform() {
// Login form setup
$loginform_data = array();
$loginform_data['attributes'] = array('id' => 'loginform');
$loginform_data['username'] = array(
'name' => 'username',
'id' => 'username',
'value' => '',
'maxlength' => '100'
);
$loginform_data['pass'] = array(
'name' => 'pass',
'id' => 'pass',
'value' => '',
'maxlength' => '100'
);
$contentdata = array();
$contentdata['loginform'] = $this->load->view('partials/forms/login', $loginform_data, true);
return $contentdata;
}
/*
* Check login username, password from form
* Parameters: void
* Return: void;
*/
public function login() {
$name = $this->input->post('username');
$pass = $this->input->post('pass');
$this->form_validation->set_rules('username', 'Användarnamn', 'required');
$this->form_validation->set_rules('pass', 'Lösenord', 'required');
if ($this->form_validation->run() == false)
{
$this->load->view('home');
}
else
{
$this->load->view('formsuccess');
}
}
}
I can call the user/login - function through the url. But I can't call User::loginform() from another controller. Shouldn't I be able to do that?
Here's what I'm trying: (from my Home-class)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
//Create login and register-forms
$this->load->helper('form');
//Registration form setup
$registerform_data = array();
$registerform_data['attributes'] = array('id' => 'registerform');
$registerform_data['company'] = array(
'name' => 'name-company',
'id' => 'name-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['orgnr'] = array(
'name' => 'orgnr-company',
'id' => 'orgnr-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['contact'] = array(
'name' => 'contact-company',
'id' => 'contact-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['phonecompany'] = array(
'name' => 'phone-company',
'id' => 'phone-company',
'value' => '',
'maxlength' => '100'
);
$registerform_data['emailcompany'] = array(
'name' => 'email-company',
'id' => 'email-company',
'value' => '',
'maxlength' => '100'
);
//What content to pass to view
$contentdata = array();
$contentdata['loginform'] = User::loginform();
$contentdata['registerform'] = $this->load->view('partials/forms/registration', $registerform_data, true);
$this->load->view('home', $contentdata);
}
}
$contentdata['loginform'] = User::loginform(); gives me error:Fatal error: Class 'User' not found in C:\Program...
What am I missing?
While you are extending Home class ,extend to User controller like
require_once(APPPATH.'controllers/user.php');
class Home extends User {
Because you need to extract the function from User class and then it will Inherit the parent class User functions And since login_form is your public function in User controller,you can call this in Home controller now.And no need to use Static here I think so.
There is also an way to do this.Just write the login_form function in an helper and call it on both the controllers then your problem may solve.
Edit: As #IJas said,we need to include the controller file that you are extending.
I've created custom validation library class MY_Form_validation as MY_Form_validation.php in application/libraries as follows.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array()) {
parent::__construct($rules);
}
public function file_required($file) {
if($file['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
}
?>
In my validation function I've included following rules as follows.
public function validate() {
$this->load->library('form_validation');
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run()) {
return true;
}
return false;
}
The core validation rules are working fine but custom rule is not working. So please help me to get the soultion and Its literally wasting my time. The work would be more appreciated.
As far as i understand your function always return true. Because of $file Not $_FILES
public function file_required($file) {
if($_FILES[$file]['size']===0) {
$this->set_message('file_required', 'Uploading a file for %s is required.');
return false;
}
return true;
}
Check the rules in the function validate()
What I think it's incorrect:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|good|file_required|xss_clean'
),
);
What I think is correct:
$config = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'display_photo',
'label' => 'Display Photo',
'rules' => 'trim|file_required|xss_clean'
),
);
I think good is not a php function, or an internal codeigniter function.
Edit:
What about using:
if ($file['size'] == 0) {
Instead of
if ($file['size'] === 0) {
Using === means the value MUST BE integer 0, but if $file['size'] returns 0 as string the if won't be true, and the function always will return true.
I had the same problem and found the cause while looking in CodeIgniter's source code. It seems the writers thought that if a field didn't have "required", then it would just skip all the rules and always return that the form has validated. See it for yourself from their code:
// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
However, if you add "callback_" in front of your rule, you can still make it run, for the procedure, look here:
https://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks
I have 3 fields in my form - lets say A, B, and C. I want to set the validation rules to where if fields A and B are empty then require C. Otherwise, require A and B.
I looked up some material on this and basically I found that I can use a callback function, but I'm a little new to CodeIgniter and I can't quite figure out the syntax to write this out.
A callback is the cleanest way to handle this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class YourController extends CI_Controller {
public function save()
{
//.... Your controller method called on submit
$this->load->library('form_validation');
// Build validation rules array
$validation_rules = array(
array(
'field' => 'A',
'label' => 'Field A',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'B',
'label' => 'Field B',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'C',
'label' => 'Field C',
'rules' => 'trim|xss_clean|callback_required_inputs'
)
);
$this->form_validation->set_rules($validation_rules);
$valid = $this->form_validation->run();
// Handle $valid success (true) or failure (false)
}
public function required_inputs()
{
if( ! $this->input->post('A') AND ! $this->input->post('B') AND $this->input->post('C'))
{
$this->form_validation->set_message('required_inputs', 'Either A and B are required, or C.');
return FALSE;
}
return TRUE;
}
}
this is simple
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$post_data = $this->input->post();
$this->form_validation->set_rules('A', 'FieldA', 'required');
$this->form_validation->set_rules('B', 'FieldB', 'required');
if(!isset($post_data['A']) AND !isset($post_data['B']))
{
$this->form_validation->set_rules('C', 'FieldC', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('success');
}
}
You can do it this way as shown below, if you place the set_rules in an if construct you may have problems when you are trying to repopulate using form helpers.
function index()
{
$required='';
if(isset($this->input->post('A')) && isset($this->input->post('B')))
{
$required='required';
}
$this->form_validation->set_rules('A', 'FieldA', 'required');
$this->form_validation->set_rules('B', 'FieldB', 'required');
$this->form_validation->set_rules('C', 'FieldC', $required);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('success');
}
}