codeigniter config form_validation with subfolders not working - codeigniter

I have using a lot config form_validation file. It's working good!
But now I'm trying to get it work with controller in subfolder
/controllers/panel/users.php
My form_validation config file looks like
$config = array(
'panel/users/edit/' => array(
array('field' => 'login', 'label' => 'Логин', 'rules' => "trim|required|valid_email")
)
And my Users controller is
public function edit($user_id = FALSE)
{
if ($this->input->post('save'))
{
$this->load->library('form_validation');
if ($this->form_validation->run())
{
// Do some
}
}
}
But $this->form_validation->run() is always return FALSE

It isn't designed to work this way, there was a relevant change to ruri_string() #122 which would have fixed this but it had other repercussions and needs to be rethought.
You can call your validation rule group explicitly (drop the trailing slash from your rule group name)
if ($this->form_validation->run('panel/users/edit'))
or, if appropriate in your situation, workaround this by prepending uri->segment(1) to the auto-detected rule group.
application/libraries/MY_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function run($group = '')
{
// Prepend URI to match subfolder controller validation rules
$uri = ($group == '') ? $this->CI->uri->segment(1) . $this->CI->uri->ruri_string() : $group;
return parent::run($uri);
}
}

Related

Adding Parameters in Routing URL Codeigniter

I have some problem with routing and parameters.
I have routing in routes.php like this :
$route['register/(:any)'] = 'member/register/$1';
And in my controller I have like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Register extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Page_model');
$this->load->model('member_model');
$this->load->model('login_model');
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('html');
$this->load->helper('form');
}
public function index()
{
$slug = $this->uri->segment(1);
$type = $this->uri->segment(2);
var_dump($type);
exit();
if ($slug != NULL)
{
$data['page'] = $this->Page_model->get_page($slug);
if (empty($data['page']))
{
// show_404();
$data['page'] = new stdClass();
$data['page']->page_template = 'forofor';
$data['page']->title = 'Page Not Found';
$data['page']->meta_description = 'Page Not Found';
$data['page']->meta_keywords = 'Page Not Found';
}
else
{
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
}
else
{
$data['page'] = $this->Page_model->get_page('home');
$data['slider'] = $this->Page_model->get_slider($data['page']->page_id);
}
$data['head_title'] = $data['page']->title;
// load all settings and data
$data['settings'] = $this->Page_model->get_settings();
$data['gallery'] = $this->Page_model->get_gallery();
$data['meta'] =
array(
array(
'name' => 'description',
'content' => $data['page']->meta_description
),
array(
'name' => 'keywords',
'content' => $data['page']->meta_keywords
)
);
// $data['meta'] = $this->meta;
$data['menu'] = $this->Page_model->get_menu('frontend','header');
$data['settings'] = $this->Page_model->get_settings();
$data['notice'] = $this->session->flashdata('notice');
// $this->load->view('frontend/template/index_full', $data);
$this->load->view('frontend/template/head', $data);
$this->load->view('frontend/template/pre_header');
$this->load->view('frontend/template/header');
$this->load->view('frontend/template/modal');
//$this->load->view('frontend/template/modal_registration');
/*if ($page[0]->page_template != 'forofor' && $data['page']->slider != 0)
{
$this->load->view('frontend/template/slider');
}*/
if ($slug != 'home' && $slug != NULL)
{
//$this->load->view('member/'.$data['page']->page_template);
$this->load->view('member/register');
}
else
{
$this->load->view('frontend/template/slider');
$this->load->view('frontend/page_template/homepage');
}
$this->load->view('frontend/template/pre_footer');
$this->load->view('frontend/template/footer');
$this->load->view('frontend/template/js');
$this->load->view('frontend/template/closing_body_html');
}
}
But if I input the routes in my browser it gives me 404 Page not found
This is my routes :
127.0.0.1/project/register/buyer
And 127.0.0.1/project/ is my Base URL
Anyone knows why it could be happen ?
Thank you.
Your routing is wrong. According to your post you are setting Member controller then register method.
Try below code
$route['register/(:any)'] = 'register/index/$1';
$route['register/(:any)/(:any)'] = 'register/index/$1/$2'; // Optional
The second option is only optional:
This is how routes work in Codeigniter
Typically there is a one-to-one relationship between a URL string and
its corresponding controller class/method. The segments in a URI
normally follow this pattern:
example.com/class/function/id/ In some instances, however, you may
want to remap this relationship so that a different class/method can
be called instead of the one corresponding to the URL.
For example, let’s say you want your URLs to have this prototype:
example.com/product/1/ example.com/product/2/ example.com/product/3/
example.com/product/4/ Normally the second segment of the URL is
reserved for the method name, but in the example above it instead has
a product ID. To overcome this, CodeIgniter allows you to remap the
URI handler.
Reference : https://www.codeigniter.com/userguide3/general/routing.html
So,the routes follow this syntax
$route['route_url'] = 'controller/method/$paramater';
So,your route will be
Let me know your queries
$route['register/(:any)'] = 'register/index/$1';

How to check all database for availability in CI 2

I have config file database.php with 5 databases.
How can I get 500 error with message "Site is not available" in all pages, if one of a database is not available?
I found it very interesting your question and have been doing some research to solve your problem.
I tell you my solution: the first is to activate the hooks, so in your config.php file make this change:
$config['enable_hooks'] = TRUE;
Once activated the hooks, you need to create a new hook, for it in the file config/hooks.php put something like the following:
$hook['post_controller_constructor'] = array(
'class' => 'DBTest',
'function' => 'index',
'filename' => 'dbtest.php',
'filepath' => 'hooks',
'params' => array(),
);
Thus, your hook kicks in once the controller has been instantiated, but has run no method yet. This is neccesary to use $CI = &get_instance()
To finish create the file /application/hooks/dbtest.php with content similar to the following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class DBTest {
function index() {
$CI = &get_instance();
$databases = array(
'mysqli://user1:pass1#host1/db1',
'mysqli://user2:pass2#host2/db2',
'mysqli://user3:pass3#host3/db3',
'mysqli://user4:pass4#host4/db4',
'mysqli://user5:pass5#host5/db5',
);
foreach ($databases as $dsn) {
$db_name = substr(strrchr($dsn, '/'), 1);
$CI->load->database($dsn);
$CI->load->dbutil();
if(!$CI->dbutil->database_exists($db_name)) {
// if connection details incorrect show error
show_error("Site is not available: can't connect to database $db_name");
}
}
}
}
You must use dsn for $CI->load->database() in this way we can handle the error instead of Code Igniter when it tries to load the database.
Hope this helps.

Passing parameters when initializing a library in Codeigniter

I am really new to Codeigniter, and just learning from scratch. In the CI docs it says:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
Can you give me simple example how to pass data from controller to external library using array as parameters? I'd like to see a simple example.
All Codeigniter "library" constructors expect a single argument: an array of parameters, which are usually passed while loading the class with CI's loader, as in your example:
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
I'm guessing you're confused about the "Do something with $params" part. It's not necessary to pass in any params, but if you do you might use them like this:
class Someclass {
public $color = 'blue'; //default color
public $size = 'small'; //default size
public function __construct($params)
{
foreach ($params as $property => $value)
{
$this->$property = $value;
}
// Size is now "large", color is "red"
}
}
You can always re-initialize later like so, if you need to:
$this->load->library('Someclass');
$this->Someclass->__construct($params);
Another thing to note is that if you have a config file that matches the name of your class, that configuration will be loaded automatically. So for example, if you have the file application/config/someclass.php:
$config['size'] = 'medium';
$config['color'] = 'green';
// etc.
This config will be automatically passed to the class constructor of "someclass" when it is loaded.
In libraries directory create one file Someclass_lib.php
Here is your Library code
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Someclass_lib
{
public $type = '';
public $color = '';
function Someclass_lib($params)
{
$this->CI =& get_instance();
$this->type = $params['type'];
$this->color = $params['color'];
}
}
Use this code when you want to load library
$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass_lib', $params);

codeigniter datamapper relationship validation issues

I need to set up the validation rules to validate the related items on a specific object, ie: A user can have no more than 3 products related to it.
I believe DataMapper can check for this validation using _related_max_size rule, but I can't figure out how to use it on the $validation array in the model.
So far I've tried this in both my user and product models:
var $validation = array(
'product' => array(
'rules' => array('max_size' => 3)
)
);
Can somebody show me an example on how to set up this at the model, controller and finally the view?
Edit: What I mean is, a user has many products, and can create a certain amount of them, let's say 3 products, when that amount is reached, the user can no longer create products, and this validation rule should not permit the user to create more products.
This would be the DB Schema:
Users table
------------------
id | username |
------------------
Products table
------------------------
id | user_id | name |
------------------------
More info here: http://codeigniter.com/forums/viewthread/178045/P500/
Thanks!
EDIT:
Ok, I got it all working now… Except, I need to do the following:
var $validation = array(
'product' => array(
'label' => 'productos',
'rules' => array('required','max_size' => $products_limit)
)
);
The $products_limit comes from the “plan” the user has associated, and it’s stored in the session when the user logs in. When I try to run this I get:
Parse error: syntax error, unexpected T_VARIABLE in /var/www/stocker/application/models/user.php on line 11
Is there any way to make this setting dynamic?
In model
var $validation = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => array('required')
)
);
In controller. $this -> $object = new Your_model();
$object->validate();
if ($object->valid)
{ $object->save();
// Validation Passed
}
else
{ $data['error'] = $object->error;
// Validation Failed
}
In view.
echo $error->field_name
I never use Codeigniter before, but give me a chance to help you. So far I didn't found any built-in validation in Code-igniter (correct me if I'm wrong).
One workaround that I could think of is to Callback:Your own Validation Functions. Below is a snip. Pardon me if it didn't work as you want.
In Model: (create something like)
function product_limit($id)
{
$this->db->where('product_id',$id);
$query = $this->db->get('products');
if ($query->num_rows() > 3){
return true;
}
else{
return false;
}
}
In controller: (create something like)
function productkey_limit($id)
{
$this->product_model->product_exists($id);
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'callback_product_limit');
}
For more information Please refer to the manual page which gives more complete. I am also new to CodeIgniter. But I hope this helps you, not complicate you.
First, set up a custom validation rule in libraries/MY_Form_validation.php
If the file doesn't exist, create it.
Contents of MY_Form_validation.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function valid_num_products()
{
//Perhaps it would be better to store a maxProducts column in your users table. That way, every user can have a different max products? (just a thought). For now, let's be static.
$maxProducts = 3;
//The $this object is not available in libraries, you must request an instance of CI then, $this will be known as $CI...Yes the ampersand is correct, you want it by reference because it's huge.
$CI =& get_instance();
//Assumptions: You have stored logged in user details in the global data array & You have installed DataMapper + Set up your Product and User models.
$p = new Product();
$count = $p->where('user_id', $CI->data['user']['id'])->count();
if($count>=$maxProducts) return false;
else return true;
}
}
Next, set up your rule in config/form_validation.php.
Contents of form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array
(
'addProduct' => array
(
array
(
'field' => 'name',
'label' => 'Product Name',
'rules' => 'required|valid_num_products'
)
)
);
Next, set up your error message in language/english/form_validation_lang.php. Add the following line:
$lang['valid_num_products'] = "Sorry, you have exceeded your maximum number of allowable products.";
Now in the Controller, you'll want something along the lines of:
class Products extends MY_In_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function add()
{
$p = $this->input->post();
//was there even a post to the server?
if($p){
//yes there was a post to the server. run form validation.
if($this->form_validation->run('addProduct')){
//it's safe to add. grab the user, create the product and save the relationship.
$u = new User($this->data['user']['id']);
$x = new Product();
$x->name = $p['name'];
$x->save($u);
}
else{
//there was an error. should print the error message we wrote above.
echo validation_errors();
}
}
}
}
Finally, you might wonder why I've inherited from MY_In_Controller. There is an excellent article written by Phil Sturgeon over on his blog entitled Keeping It Dry. In the post he explains how to write controllers that inherit from access-controlling Controllers. By using this paradigm, controllers that inherit from MY_In_Controller can be assumed to be logged in, and the $this->data['user']['id'] stuff is therefore assumed to be available. In fact, $this->data['user']['id'] is SET in MY_In_Controller. This helps you seperate your logic in such a way that you're not checking for logged in status in the constructors of your controllers, or (even worse) in the functions of them.

Codeigniter form validation config file not working

I'm using the technique of saving codeigniter form validation rules to a config file as specified here, but can't seem to get it working.
I am also attempting to invoke validation callback functions from a Validation_Callbacks.php library which I'm autoloading via the autoload.php mechanism.
Below is a snippet from my form_validation.php form validation rules config file:
<?php
/* This config file contains the form validation sets used by the application */
$config = array(
'register_user' => array(
array(
'field' => 'dob',
'label' => 'lang:register_dob',
'rules' => 'trim|required|date_check|age_check|xss_clean'
), ...
)
)
And here is the Validation_Callbacks.php file, that lives under application/libraries:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Custom validator library containing app-specific validation functions
*/
class Validation_Callbacks {
/* Checks that the given date string is formatted as expected */
function date_check($date) {
$ddmmyyyy='(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)[0-9]{2}';
if(preg_match("/$ddmmyyyy$/", $date)) {
return TRUE;
} else {
$this->form_validation->set_message('date_check', $this->lang->line('error_register_dob_format'));
return FALSE;
}
}
/* Checks that the given birthday belongs to someone older than 18 years old. We assume
* that the date_check method has already been run, and that the given date is in the
* expected format of dd/mm/yyyy */
function age_check($date) {
$piecesDate = explode('/', $date);
$piecesNow = array(date("d"), date("m"), date("Y"));
$jdDate = gregoriantojd($piecesDate[1], $piecesDate[0], $piecesDate[2]);
$jdNow = gregoriantojd($piecesNow[1], $piecesNow[0], $piecesNow[2]);
$dayDiff = $jdNow - $jdDate;
if ($dayDiff >= 6570) {
return TRUE;
} else {
$this->form_validation->set_message('age_check', $this->lang->line('error_register_age_check'));
return FALSE;
}
}
}
I'm invoking this using the standard:
if ($this->form_validation->run('register_user') == FALSE) {
My callback functions are not being called. Is there something I'm missing here? Thanks in advance for any help you may be able to provide!
Ensure that:
When a rule group is named identically
to a controller class/function it will
be used automatically when the run()
function is invoked from that
class/function.
To test you can try using:
$this->load->config('configname');

Resources