Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter 3 - Extending Form Validation not working
#1

MY_Form_validation.php in the folder application/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();
$this->_config_rules = $config;
   }

  // --------------------------------------------------------------------
 

  /**
* required_if
*
* @access public
* @param string $str
* @param string $field
* @return bool
*/
function required_if($str, $field)
{
$this->CI->my_form_validation->set_message('required_if', $this->CI->lang->line('con_the').' '.'%s'.' '.$this->CI->lang->line('not_field_required'));
if ( ! is_array($str))
{
return (trim($str) == '') ? FALSE : TRUE;
}
else
{
return ( ! empty($str));
}
}

//-----------------------------------------------------------
}

?>
--------------------------------------------------

my view file:
===========

<!-- start - forms -->
<div class="forms lt" style="width:49%">
<?php
$form_attributes = array(
"id" => "reg_form",
"name" => "reg_form",
"method" => "post",
);
echo form_open(base_url()."user/login", $form_attributes);
?>
   <div class="subtitle"><?=$this->lang->line('con_login')?></div>
   
   <!-- start - form_fields -->
   <div class="form_fields">
   
       <div class="row">
           <div class="label"><?=$this->lang->line('con_username')?> / <?=$this->lang->line('con_email')?> <span class="mand">*</span></div>
           <div class="field"><input id="username" name="username" type="text" value="<?= set_value('username') ?>" /></div>
           
       </div>
       
       <div class="row">
           <div class="label"><?=$this->lang->line('con_password')?> <span class="mand">*</span></div>
           <div class="field"><input id="password" name="password" type="password" value="<?= set_value('password') ?>" /></div>
         
       </div>
       
       <div class="row">
          <input type="submit" id="submit" name="submit" value="login"  />
       </div>

   </div>
   <!-- end - form_fields -->
   <?=form_close()?>
</div>
<!-- end - forms -->

----------------------------------------------------------

my controller function:
===============

class User extends MY_Controller {

function __construct()
     {
        parent::__construct();
      }

function login()
{
$this->CI =& get_instance();
$this->CI->load->library('my_form_validation');
if( ! $this->session->userdata('logged_in'))
{
if($this->input->post('submit'))
{
$config_rules = array(
array(
'field' => 'username',
'label' => $this->lang->line('con_username'),
'rules' => 'required_if' ),
array(
'field' => 'password',
'label' => $this->lang->line('con_password'),
'rules' => 'required_if'),
);

$this->CI->my_form_validation->set_rules($config_rules);  
$this->CI->my_form_validation->set_error_delimiters('<span class="terr">', '</span>');
if($this->form_validation->run())
{}
}      }        }
}

I got following errors

A PHP Error was encountered

Severity: Notice

Message: Undefined property: User::$my_form_validation

Filename: user/login.php

Line Number: 15


( ! ) Fatal error: Call to a member function error() on a non-object in D:\wamp\www\getcommun\application\views\user\login.php on line 15

A PHP Error was encountered

Severity: Error

Message: Call to a member function error() on a non-object

Filename: user/login.php

Line Number: 15

Any please help me its very urgent.....
Reply
#2

You don't load "My_form_validation", you just load form_validation like normal. CI will internally load MY_Form_validation IF it exists.

You also still just use the "form_validation" object, like here:
$this->CI->my_form_validation->set_rules($config_rules);

Just make sure the MY_Form_validation.php file exists in /application/libraries, since it's a CI native library you are extending.
Reply
#3

Dear CroNiX,

First i thanks to you for replied my message.

I got another Isssue.

application/libraries/MY_Form_validation.php
=================================

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//include_once BASEPATH . '/libraries/Form_validation.php';

class MY_Form_validation extends CI_Form_validation {

public function __construct($rules = array())
{
parent::__construct();
$this->CI =& get_instance();
$this->_config_rules = $rules;
}

public function is_required($str)
{
if(empty($str))
{
$this->CI->form_validation->set_message('is_required', 'The %s is required');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>

Controller/User.php
=============
class User extends MY_Controller {

function __construct()
{
parent::__construct();
$this->CI =& get_instance();

}
function login()
{
if($this->input->post('submit'))
{
$this->CI->form_validation->set_rules('username', 'Username', 'is_required');
$this->CI->form_validation->set_rules('password', 'Password', 'is_required');
if ($this->CI->form_validation->run() == FALSE)
{
echo " Failed <br/>";
}
else
{
echo " Success <br/>";
}
}
}
}

core/MY_Controller.php
=====================

class MY_Controller extends CI_Controller {

// html header variables
public $title;
public $keywords;
public $description;

// template specific dynamic variables
public $current_menu;
public $current_sub_menu;
public $doc_heading;
public $breadcrumbs;
public $template_msg;
public $template_err;
public $content;
public $ajax = FALSE;

// js and css specific variables
public $onload_js;
public $internal_css;
public $internal_js;
public $tbname;


function __construct()
{

parent::__construct();

// CodeIgniter libraries and helpers

$this->load->helper(array('security', 'form', 'url', 'date', 'download', 'file', 'language'));

// Userdefined project specific helpers

$this->load->helper(array('ui', 'constants'));

//Load userdefined model

$this->load->model('process'); //process related data

//Load validation library
$this->load->library(array('session', 'upload', 'form_validation', 'pagination', 'email', 'image_lib'));
}
}

=================

Vie file a same as previous message.

Output:
if i am submit form with empty fileds,then i got "SUCCESS".

How can this execute. I think , it does not call MY_Form_validation 's is_required().
Please help me CroNiX.
Reply
#4

First, fix the constructor for MY_Form_validation:
PHP Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class 
MY_Form_validation extends CI_Form_validation 
{
 
   public function __construct($rules = array())
 
   {
 
       // Pass the $rules to the parent constructor.
 
       parent::__construct($rules);
 
       // $this->CI is assigned in the parent constructor, no need to do it here.
 
   }

 
   public function is_required($str)
 
   {
 
       if (empty($str))
 
       {
 
           $this->CI->form_validation->set_message('is_required''The %s is required');
 
           return FALSE;
 
       }

 
       return TRUE;
 
   }


and the User controller:
PHP Code:
<?php
class User extends MY_Controller {

 
   public function __construct()
 
   {
 
       parent::__construct();
 
       // No need to use get_instance() in a controller 
 
       // which extends a child of CI_Controller.
 
   }

 
   public function login()
 
   {
 
       if ($this->input->post('submit'))
 
       {
 
           $this->form_validation->set_rules('username''Username''is_required');
 
           $this->form_validation->set_rules('password''Password''is_required');
 
           if ($this->form_validation->run() === FALSE)
 
           {
 
               echo " Failed <br/>";
 
           }
 
           else
            
{
 
               echo " Success <br/>";
 
           }
 
       }
 
   }


However, the problem may simply be in your is_required() method's logic, as empty() isn't necessarily going to give you the expected result. This is why CI's Form_validation->required() method looks like this:
PHP Code:
    public function required($str)
    {
        return 
is_array($str) ? (bool) count($str) : (trim($str) !== '');
    } 
Reply
#5

MY_Form_validation should go in application/core if you are extending the built-in one.
Reply
#6

(This post was last modified: 09-04-2015, 11:42 AM by mwhitney.)

(09-04-2015, 11:33 AM)ciadmin Wrote: MY_Form_validation should go in application/core if you are extending the built-in one.

That doesn't sound right. Since it's loaded via $this->load->library('form_validation'), the library() method would call _ci_load_library(), which, in turn, would call _ci_load_stock_library(), which eventually does this:

PHP Code:
        $paths $this->_ci_library_paths;

        array_pop($paths); // BASEPATH
        array_pop($paths); // APPPATH (needs to be the first path checked)
        array_unshift($pathsAPPPATH);

        foreach ($paths as $path)
        {
            if (file_exists($path $path.'libraries/'.$file_path.$library_name.'.php'))
            {
                // Override
                include_once($path);
                if (class_exists($prefix.$library_nameFALSE))
                {
                    return $this->_ci_init_library($library_name$prefix$params$object_name);
                }
                else
                
{
                    log_message('debug'$path.' exists, but does not declare '.$prefix.$library_name);
                }
            }
        


In general, when overloading system classes you just put the file in the equivalent directory in application. In other words, you would override /system/libraries/Form_validation.php with /application/libraries/MY_Form_validation.php
Reply
#7

(This post was last modified: 09-05-2015, 04:47 AM by InsiteFX.)

ciadmin is correct here, if you extended a ci library it goes under the application/core folder ( MY_name library goes in CORE ).

Everything else goes in there rightful folders. ( MY_name_helper etc; ).

Your own libraries go in the library folder.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#8

(09-05-2015, 04:45 AM)InsiteFX Wrote: ciadmin is correct here, if you extended a ci library it goes under the application/core folder ( MY_name library goes in CORE ).

Everything else goes in there rightful folders. ( MY_name_helper etc; ).

Your own libraries go in the library folder.

No, mwhitney is correct here.

Wherever the library is located under system/, the same directory path must be replicated under application/ in order to extend/override it.
Reply
#9

Thanks to mwhitney . Its working fine now
Reply
#10

mwhitney is correct! My bad - I was thinking of the core classes Undecided
Reply




Theme © iAndrew 2016 - Forum software by © MyBB