Extending form validation rule in codeigniter - codeigniter

I have a form with two fields
<input type="text" name="total_plots" value="" placeholder="Enter Total plots" />
<input type="text" name="available_plots" value="" placeholder="Enter Available Plots " />
Available plot "available_plots" field value should be less than total plots "total_plots" field value
I don't want to write callbacks. I want to extend the form validation rule.
How to ?
MY_Form_validation
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
$this->CI =& get_instance();
}
public function check_avail($str)
{
$this->CI->form_validation->set_message('check_avail', 'Available plot should be less than Total plot.');
$total_plots = $this->CI->input->post('total_plots');
//echo '------'.$total_plots;
//echo '------'.$str;
if($str > $total_plots){
return false;
}
}
} // class
I have written rules in config
<?php
$config['plot_settings'] = array(
array(
'field' => 'total_plots',
'label' => 'Total Plots',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'available_plots',
'label' => 'Available Plots',
'rules' => 'trim|xss_clean|check_avail'
)
);
?>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Plot extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('Admin_layout');
$this->load->model('admin/plot_model');
$this->config->load('plot_rules');
$this->output->enable_profiler(TRUE);
$this->new_name='';
}
public function add(){
$this->form_validation->set_rules($this->config->item('plot_settings'));
$this->form_validation->set_error_delimiters('<p><b>', '</b></p>');
if ($this->form_validation->run('submit') == FALSE )
{
$this->admin_layout->set_title('Post Plot');
$this->admin_layout->view('admin/post_plot');
}
}//add
}

I think you can do this without writing a callback or extending the validation rule.
CI already provides a validation rule to check for less_than value.
$total_plots = $this->input->post('total_plots');
$this->form_validation->set_rules('available_plots', 'Available Plots', "less_than[$total_plots]");
It should work.

Related

Validation message not showing below the field in cakephp 3 latest version

I am trying to validate a multiple select field that have jquery chosen applied.
Validation is working perfectly but only problem is that validation message is not showing below the input field.
Here is my files.
profile_edit.ctp
<?php echo $this->Form->create($user,['action' => '', 'role'=>"form",'novalidate'=>true,'method'=>'post','id'=>'ProfileForm','templates'=>['label'=>false,'inputContainer'=>'{{content}}']]); ?>
<?php echo $this->Form->control('user_grades[].grade_id',['multiple','hiddenField'=>false, 'escape'=>false, 'type'=>'select', 'id'=>'sp_grade', 'options'=>App\Model\Table\GradesTable::getGrades('list'),'class'=>'form-control chosen-select']); ?>
<button type="submit" class="btn footer_btns float-left">Save</button>
<?php echo $this->Form->end(); ?>
MyAccountController.php
<?php
public function profileEdit(){
$user = $this->Users->get($this->Auth->user('id'), ['contain'=>['UserGrades']]);
if($this->request->is(['put','post'])){
$data = $this->request->getData();
if(isset($data['user_grades']) && !empty($data['user_grades'])) {
$this->UserGrades->deleteAll(['user_id' => $this->Auth->user('id')]);
}
if(null == $this->request->getData('user_grades')){
$this->request = $this->request->withData('user_grades.0.grade_id','');
}
$user = $this->Users->patchEntity($user, $this->request->getData(), [
'validate' => 'editProfileSection',
'associated' => [
'UserGrades' => ['validate'=> 'editProfileSection']
]
]);
if(empty($user->getErrors())){
if ($this->Users->save($user)) {
$this->Flash->success(__('Succesfully updated <strong>'.$user->full_name .'</strong> Information||Success'));
return $this->redirect(['action' => '']);
}
}
$this->Flash->error(__('Please check your inputs and try again.||Action Failed!'));
}
$this->set(compact('user'));
}
UserGradesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
use Cake\ORM\RulesChecker;
use Cake\Validation\Validator;
class UserGradesTable extends Table {
public function initialize(array $config) {
$this->addBehavior('Timestamp');
$this->addBehavior('Trim');
}
public function validationEditProfileSection(Validator $validator) {
$validator
->notEmpty('grade_id',"Please select at least one grade.");
return $validator;
}
}
I have tried to get error message and got following:
Array
(
[user_grades] => Array
(
[0] => Array
(
[grade_id] => Array
(
[_empty] => Please select at least one grade.
)
)
)
)
But this error is not showing below the input field. Any help will be appreciated.
You are not using the correct naming scheme for the form control, you cannot use [], if you want the form helper magic to work, then you must supply the actual index, ie:
user_grades.0.grade_id
See also Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

Codeigniter redirect method is not working

This is my User.php controller
I am unable to use redirect method.
i am working on xampp localhost
?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->library('Admin_layout');
$this->config->load('reg_rules');
$this->load->model('admin/user_model');
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
if (!$this->auth->loggedin()) {
redirect('admin/login');
}
}
public function add(){
//if($this->input->post('submit')){
$this->form_validation->set_rules($this->config->item('reg_settings'));
$data["reg_attrib"] = $this->config->item("reg_attribute");
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run('submit') == FALSE)
{
// templating
$this->admin_layout->set_title('Add a User');
$this->admin_layout->view('admin/add_user',$data["reg_attrib"]);
// templating
}
else
{
// Develop the array of post data and send to the model.
$passw = $this->input->post('password');
$hashpassword = $this->hash($passw);
$user_data = array(
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('contact_no'),
'email' => $this->input->post('email'),
'password' => $this->hash($hashpassword),
'doj' => time(),
);
$user_id = $this->user_model->create_user($user_data);
Here i am setting my success message using set_flashdata
and redirecting
if($user_id){
$this->session->set_flashdata('item', 'Record created successfully');
$this->redirect('admin/user/add','refresh');
}else{
echo "User Registration Failed!";
}
}//else
//} // submit
} // add
}
View_users.php
<?php
if($this->session->flashdata('item'))
{
echo $message = $this->session->flashdata('item');
}
?>
I am getting the following error
Fatal error: Call to undefined method User::redirect() in C:\xampp\htdocs\ci\application\controllers\admin\User.php on line 67
A PHP Error was encountered
Severity: Error
Message: Call to undefined method User::redirect()
Filename: admin/User.php
Line Number: 67
Backtrace:
Try to change from
$this->redirect('admin/user/add','refresh');
to
redirect('admin/user/add','refresh');
Hope it will be useful for you.

How to write component in codeigniter

I want to know how can I write a component in codeigniter
I have worked with symfony1.4 and there there is something include_component("name",dataarray()) that we can load a component ( it's actually an action ).
I already know that we have $this->load->view('admin/template/login') for loading a view, But I want to know is there any way to call an action like this?
this->load(news/list,array('date'=>xxx-xx-xx))
thanks anyways
you can this through the use of libraries, helpers or plugins.
an example of using a library class in application/library called LoadNews.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class LoadNews {
public function showList($date_array) {
// do stuff with date array
}
}
/* End of file LoadNews.php */
/* Location: ./application/libraries/LoadNews.php */
then in your controller, you call
$this->load->library('LoadNews');
$this->loadnews->showList(array('date'=>'2014-12-19'));
Yes, you can do this from CI 3.
In your Controller or View just call $this->load->view(view, data);
Example:
<?php
defined('BASEPATH') or die('No direct script allowed');
class PageController extends CI_Controller
{
public function index()
{
$data = [
'names' => ['john', 'doe'],
'ages' => ['24', '30']
];
$this->load->view('index', $data);
}
}
?>
And in your view you can access 'names' and 'ages' as $names and $ages respectively.
You can do this in your view:
<?php
echo '<pre>';
print_r($names);
print_r($ages);
echo '</pre>';
?>
The result:
Array (
[0] => john
[1] => doe
)
Array (
[0] => 24
[1] => 30
)

Yii Framework: validate checkbox on view page

I'm new to the Yii Framework. Currently, I'm having a project which require me to use Yii framework. I would like to ask, is it possible for me to validate an attribute which is not save inside the database?
case:
I have a checkbox which require the user to tick on it in order to move to the next page. If the user doesn't tick on it, then it will prompt an error. How to I validate it in Yii format?
Can someone teach me how to change the validation below to fit Yii Format? where should the validation locate?
content in model.php
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
content in view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<p class="cb_pdpa" style="font-weight:bold"><?php echo $form->checkbox($data,'pdpa_agree'); ?> I have read and understood the above policies and hereby give consent for CTES to use my <pd>*personal data</pd> in accordance to the policies listed out above.</p>
<div class="form-actions">
<?php
/*$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'submit',
'type' => 'primary',
'label'=>$model->isNewRecord ? 'PolicyAgreement' : 'Continue Registration',
));*/
?>
<input type="button" name="submit" value="Continue Registration" onclick="validateAgreement()">
</div>
<?php $this->endWidget(); ?>
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
How to turn to validation below to fit Yii Format?
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
Yeah you can validate
Model.php
Delclare the variable you want to use
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
public function attributeLabels()
{
return array(
'pdpa_agree' => 'I have read and understood the above policies and hereby give consent for CTES to use my *personal data in accordance to the policies listed out above',
);
}
MyController.php
public function actionRegistration(){
$model = new Model();
if(isset($_POST['Model'])){
//Stuff to save Goes here
}
$this->render('registration');
}
view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<div class="form-actions">
$form->checkBox($model,'checkBox');
$form->labelEx($model,'checkBox');
$form->error($model,'checkBox');
</div>
<?php $this->endWidget(); ?>

codeigniter config form_validation with subfolders not working

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);
}
}

Resources