I get field was not set error when I'm validating a form
Here is my view
<div class="panel-body">
<h3>Basic Information</h3>
<?php $atrrib = array('class' => 'form-horizontal','role' => 'form');?>
<?php echo form_open('school/shule',$atrrib);?>
<div class="col-md-6">
<div class="form-group">
<label for="add_name" class="col-md-2 control-label">School:</label>
<div class="col-md-7">
<input type="text" class="form-control" name="add_name" id="addSchoolName" placeholder="School name">
</div>
</div>
</div>
<button type="submit" class="btn btn-default">Next</button>
<?php echo form_close();?>
</div>
</div>
</div>
<div class="col-md-2"><?php include_once (APPPATH. 'views/admin/admin_right_column.php');?></div>
</div>
Here is my controller
class School extends CI_Controller {
public function __construct() {
parent::__construct();
}// End of construct
public function shule(){
$this->load->library('form_validation');
if($this->form_validation->run('first_form') === TRUE){
echo 'Valid';
}
else{
if(validation_errors()){
echo validation_errors();
}
$data['title'] = "Add School";
$data['page'] = "admin| add school";
$this->load->view('admin/admin_header',$data);
$this->load->view('admin/add_school',$data);
$this->load->view('admin/admin_footer');
}
}
}
Here is my form_validation configuration
$config['first_form'] = array(
array(
'field' => 'add_name',
'label' => 'School name',
'rules' => 'required|xss_clean|min_length[2]'
)
);
I get an field was not set error when I left the field blank and also I get an Unable to access an error message corresponding to your field name error when I input a single char.
I tried looking where CI fire up your error
Unable to access an error message corresponding to your field name
Then I found this
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
So this means CI checks if you have not set rule message to the field then check if there is a line that corresponds to the fired function/rule in the form_validation_lang.php file .
So I assumed CI does not find the error message corresponding to your field name because
You have edited/deleted line with the name of the callback/rule
You have created another language file under /application/language with the same name as the default form_validation_lang and haven't defined the rule corresponding to your field name .
Solution is to cross check your lang file if it has a line defined with the same name as your rule or delete any custom language file that has the same name as form_validation_lang.php or you can add up a rule such as
$lang['required'] = 'Name field is required";
or any other rule you have defined in your validation file/function in your custom language file .
try
$this->form_validation->set_rules('add_name', 'School name', 'trim|required||min_length[2]');
if ($this->form_validation->run() == TRUE){
echo 'Valid';
}
else {
$data['title'] = "Add School";
$data['page'] = "admin| add school";
$this->load->view('admin/admin_header',$data);
$this->load->view('admin/add_school',$data);
$this->load->view('admin/admin_footer');
}
and check for errors on view
if(validation_errors()){
echo validation_errors();
}
You can set a custom error message with set_message and use the label from the set_rules function. You can find the documentation here.
Here is an example:
// Set the validation rule
$this->form_validation->set_rules('project_name', 'Project Name', 'trim|required');
// Set the custom message with %s where the label should go
$this->form_validation->set_message('required', '%s is required. Please enter a value.');
// For an invalid project_name, you will get the error:
// Project Name is required. Please enter a value.
Related
In my codeigniter controller function call $this->form_validation->run(), that return always false, and my validation_errors() not showing error, probably because not receive datas in post method...
my controller
class Reminder extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reminder_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('email');
$this->load->library('session');
if(!$this->session->auth_ok) {
redirect('auth/login');
}
}
public function index(){
$data['title'] = 'Reminder';
$data['section'] = 'reminder';
$data['reminders'] = $this->reminder_model->getReminders();
$data['operatori'] = $this->reminder_model->getOperators();
$this->form_validation->set_rules('selectUser','selectUser', '');
if($this->form_validation->run() === FALSE) {
$this->load->view('common/header2', $data);
$this->load->view('reminder/index', $data);
$this->load->view('common/footerReminder');
echo validation_errors();
}else{
echo "<pre>";
print_r($this->input->post());
die();
}
}
my view
<?php echo form_open('reminder/index'); ?>
<div class="form-group">
<label for="selectUser" style=" width: 30%">Utente: </label>
<select class="form-control" name="selectUser" id="selectUser" style="width: 30%">
<?php foreach($operatori as $operatore): ?>
<option value="<?php echo $operatore['ID']?>" <?php echo $r = ($operatore['ID']==$this->session->auth_user['ID']) ? 'selected' : '' ?>><?php echo $operatore['nome']." ".$operatore['cognome'] ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> View</button>
<?php echo form_close(); ?>
In order to get the entire $_POST array using CodeIgniters built-in methods, you have to set the first parameter as NULL and the second parameter as TRUE
Like this:
$this->input->post(NULL, TRUE);
Also, you have not set any rules for validation..
In CodeIgniter, you set rules in the third parameter of the set_rules method within the form_validation object.
Like this:
$this->form_validation->set_rules($FIELD_NAME, $FIELD_NAME(for error messages), $RULES);
You would substitute the first $FIELD_NAME with the value of the name attribute on the HTML element you are looking to validate.
You would substitute the second $FIELD_NAME with the name you would like to use for the field when displaying an error message to the user.
You would substitute $RULES with the validation rules such as: 'required|min_length[#]|max_length[#]'
Hope this helps!
If you are not setting rules (which makes it rather pointless to use $this->form_validation->set_rules()) the form validation will fail as it's missing a required parameter.
If you don't need to validate a field, don't set a rule.
Try updating your set_rules instruction to $this->form_validation->set_rules('selectUser','selectUser', 'required'); to see if it behaves correctly. You can verify by filling something in the form (validation will pass) or leaving the field blank (validation will fail)
Just remember, if you won't set at least one validation rule for a field, don't instantiate the set_rules method for that field
I have three field in my html one is mobile_min,mobile_max and third field
i have taken is test which is a input field.So what i have to do i have to
create a custom validation with custom message in which my requirement is mobile_min value should not be greater than mobile_max value after submitting the from.So my code is working fine but i am getting this message "The Min value is not greater than max value field is required." and but i want this message "The Min value is not greater than max value field.".I have also read the custom message rule of CI but it is not working.
Html field code
<html>
<input type=text name=mobile_min>
<input type=text name=mobile_max>
<input type=hidden name=test>
</html>
Controller Validation code
<?php
if($this->input->post('mobile_min')>$this->input->post('mobile_max'))
{
$this->form_validation->set_rules('test', 'Min value is not greater than max value','trim|required');
}
?>
Please help me thanks in Advance.
Use codeigniter form validation call back https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
Controller function:
<?php
class Controllername extends CI_Controller {
public function index() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('mobile_min', 'mobile min', 'required');
$this->form_validation->set_rules('mobile_max', 'mobile max', 'required|callback_somename');
if ($this->form_validation->run() == TRUE) {
/// Success data.
}
$this->load->view('some_view');
}
public function somename() {
if($this->input->post('mobile_min') > $this->input->post('mobile_max')) {
$this->form_validation->set_message('somename', 'Min value is not greater than max value');
return FALSE;
}
}
}
View
<?php echo form_open('controllername'); ?>
<?php echo validation_errors();?>
<?php echo form_input('mobile_min', '', array('id' => 'mobile_min'));?>
<?php echo form_input('mobile_max', '', array('id' => 'mobile_max'));?>
<button type="submit" class="btn btn-primary">Submit</button>
<?php echo form_close();?>
I am trying to apply some validation rules to my form data in CodeIgniter.
Expected Allowed output example like this: 22-some society, some street, city. 223399
What I Entered for check the validation: 42-some Society-3, some street. arcade ###*
This is my function which I use to validate the address.
function addr_line1($addr_line1) {
if (preg_match('/^[a-z0-9 .\-]+$/i',$addr_line1) !== FALSE)
return TRUE;
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
return FALSE;
}
Now I put all my validation in the config/form_validation.php
array(
'field' => 'addr_line1',
'label' => 'Address Line One',
'rules' => 'required|max_length[100]|callback_addr_line1'
),
After all this,I didn't get any validation error.
Am I not following the proper process?
or what should the regex code to validate this type of data?
change from
function addr_line1($addr_line1) {
if (preg_match('/^[a-z0-9 .\-]+$/i',$addr_line1) !== FALSE)
return TRUE;
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
return FALSE;
}
to
function addr_line1($addr_line1) {
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $addr_line1))
{
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
}else{
return true;
}
}
Note:- you can replace £$%&*()}{##~?><>,|=_+¬- with your disallowed character
After Your suggestion and help, I finally found the correct Function.
function _validAddressCheck($addr_line1) {
if (preg_match('/^[0-9a-zA-Z .,-]+$/',$addr_line1)){
return TRUE;
} else {
$this->form_validation->set_message('_validAddressCheck', 'Only Allowed space, comma, dot, dash, numbers and alphabets.');
return FALSE;
}
}
I found that some rules which we have to follow if we are applying callback to the validation.
I have created config validation array at the application/config/form_validation.php
Put the callback function at the controller where I called that validations.
Find this link for creating a regex and test that. Link
<tr>
<td>
<label for="address">Address:</label></td><td>
<textarea name="address" placeholder="Write
something.."><?php echo set_value('address'); ?> </textarea>
</td>
<td>
<p class="err_msg">
<?php
echo form_error('address');
?>
</p>
</td>
in route page:-
$this->form_validation->set_rules('address','add','required|exact_length[18]',array('required'=>"Please Enter Address",'exact_length'=>"Please Enter At Least 10 Character"));
I'm working on a multiple contact form in Yii 1.1.16. Where the user can add multiple phone numbers.
Problem is, how would i validate this using Yii's rules()?
<div class="form-group">
<?php
echo $form->labelEx($model,'contacts', array('class'=>'col-md-3 control-label'));
?>
<div class="col-md-9">
<div class="multiple-contact multiple-form-group input-group padding-bottom-10px" data-max="5">
<div class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">Phone</span> <i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>Phone</li>
<li>Fax</li>
<li>Mobile</li>
</ul>
<?php echo $form->textField($model,'contacts',array('type'=>'text', 'class'=>'input-group-select-val', 'name'=>'contacts[type][]','value'=>'phone')); ?>
</div>
<?php echo $form->textField($model,'contacts',array('size'=>60,'maxlength'=>255, 'name'=>'contacts[value][]','class'=>'form-control')); ?>
<?php echo $form->error($model,'contacts'); ?>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add"><i class="fa fa-plus"></i></button>
</span>
</div>
</div>
</div>
i tried using this, but doesn't work
public function rules()
{
return array(
array('contacts[value][]', 'required'),
array('contacts[value][]', 'integerOnly'=>true),
array('contacts[value][]','type','type'=>'array','allowEmpty'=>false)
);
}
Here is a sample Fiddle on how the jQuery side works. I want it to be able to validate with 'enableAjaxValidation'=>true,. Also, when more fields are added, it duplicates the id of the input. and no ajax post is done onblur/onfocus
Use custom validation.
Declare a custom validator in your rules, and define the validation you require in the validator method.
public function rules()
{
return array(
array('contacts', validateContacts),
);
}
public function validateContacts($attribute,$params)
{
if (length($this->contacts) == 0) {
$this->addError($attribute, 'You must add at least one contact!');
}
foreach($this->contacts as $contact) {
// ...
}
}
In your controller, assign the contacts array to the Model field and call the model's validation method. If there are any errors it will display through the line
<?php echo $form->error($model,'contacts'); ?>
in the view.
The controller contains the code to invoke the validation.
$contactModel = new Contact;
// assign the array of contacts to the model
$contactModel->contacts = $POST['myForm]['contacts']
$contactsModel->validate();
$this->render('myform', contactModel);
If you want the validation to happen through Ajax, you need to specify so when creating your form:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'top-websites-cr-form',
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true),
));
In this case your controller can check for ajax forms.
if(isset($_POST['ajax']) && $_POST['ajax']==='branch-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
references:
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
You should make it a separate model with it's own validation.
Then in your controller you have to validate the main models and the related models separately.
Here is a good guide for such a setup:
http://www.yiiframework.com/wiki/384/creating-and-updating-model-and-its-related-models-in-one-form-inc-image/
To my opinion for best validation regarding phonenumbers you should use libphonenumber php library and there is an extension for it regarding yii framework here http://www.yiiframework.com/extension/libphonenumber/
basic usage:
Yii::setPathOfAlias('libphonenumber',Yii::getPathOfAlias('application.vendors.libphonenumber'));
$phonenumber=new libphonenumber\LibPhone($your_phone_number);
$phonenumber->validate();
for more details regarding usage and capabilities of libphonenumber php library you can find here:
https://github.com/davideme/libphonenumber-for-PHP
Let us consider you have a model called ContactNo and it looks like
class ContactNo extends CFormModel
{
public $contact;
public function rules()
{
return array(
// your rules
array('contact', 'required'),
array('contact','length','min'=>2)
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'contact'=>'Contact No',
);
}
}
The controller as SiteController and the action Name as actionIndex
Then your controller should look something like this
public function actionIndex()
{
// set how many contact fields you want here
$contactCount = 3;
$models = array();
if(isset($_POST['ContactNo']))
{
$successModels = 0;
foreach($_POST['ContactNo'] as $key=>$value)
{
$model = new ContactNo;
$model->attributes = $value;
if($model->validate()) // this validates your model
$successModels++; // it tells how many contact No.s have been validated
$models[$key]=$model;
}
// if all the contact nos are validated, then perform your task here
if($successModels === $contactCount)
{
// save your models
echo 'models saved';
Yii::app()->end();
}
}
else
{
for($index = 0;$index < $contactCount; $index++)
$models[] = new ContactNo;
}
$params = array();
$params['contactCount']=$contactCount;
$params['models']= $models;
$this->render('index',$params);
}
Now lets Go to view. Obviously the view is index.php and it will be something like
// Include all the initial part required for activeforms
<?php echo $form->errorSummary($models); ?>
<?php foreach ($models as $index=>$model): ?>
<div class="row">
<?php echo $form->labelEx($model,"[{$index}]contact"); ?>
<?php echo $form->textField($model,"[{$index}]contact",array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,"[{$index}]contact"); ?>
</div>
<?php endforeach; ?>
// Include the submit button
Hope this helps you or might give you an idea atleast to achieve your goal.
I want to select some data in the CodeIgnigher PHP application from the database and want to make some change and insert to another table. I would like to insert as as many as selected records into the IN table. Currently I am getting only one row inserted into the out table.
Can you please point, what is being done wrong here.
My tables are. Out_Table (id, name..) and In_Table (id, name, quantity..).
My Model Code is:
<?php
class ShoppingListM extends CI_Model {
public function getData() {
$query = $this->db->get('products');
return $query->result();
}
function SaveForm($form_data) {
$this->db->insert('SLists', $form_data);
if ($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
}
?>
View Code:
<div class="divTable">
<fieldset>
<!-- these will be affected by check all -->
<div class="divRow">Product Name | Quantity | Packages</div>
<div class="divRow"><input type="checkbox" size="100" class="checkall"> Check all</div>
<br>
<?php foreach ($records as $rec) {
?>
<div class="divRow"><input type="checkbox">
<input size="5" type="hidden" value="<? echo $rec->id; ?>" name="id"></input>
<input size="20" type="text" value="<? echo $rec->name; ?>" name="name"></input>
<input size="5" type="text" value="" name="quantity"></input>
<select name="package">
<option name="case">Case</option>
<option name="box">Box</option>
<option name="box">Single Bottle</option>
</select>
</div>
<br>
<?
}
?>
</fieldset>
</div>
<div><input type="submit" name="submit"/></div>
</form>
Controller Code:
class ShoppingListController extends CI_Controller {
public function index() {
//$data['val'] = array("test1", "test2", "test3");
// $this->load->model('HomeModel');
//$data['records'] = $this->HomeModel->getData();
$this->load->model('ShoppingListM');
$data['records'] = $this->ShoppingListM->getData();
$this->form_validation->set_rules('name', 'Name', 'required|max_length[255]');
$this->form_validation->set_rules('qty', 'qty', '');
$this->form_validation->set_rules('package', 'Package', 'required|max_length[128]');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('ShoppingListV', $data);
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'name' => set_value('name'),
'quantity' => set_value('quantity'),
'package' => set_value('package')
);
// run insert model to write data to db
// run insert model to write data to db
if ($this->ShoppingListM->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('ShoppingListController/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
well i cannt see where is in_table/out_table in the code u provided yet.
to insert many rows what u want insert_batch
example from doc
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
or u can loop all ur rows from in_table and insert them one by one if its a maintaince job that u dont care about multiple queries
$data= $this->db->get('Out_table');
try
{
if ( $data->num_rows == 0)
throw new Exception('table empty');
foreach( $data->result() as $row)
{
//modifiy the row as u want
$modified=$row;
$q=$this->db->insert('in_table',$modified);
if( ! $q )
throw new Exception('failed to insert row id:'.$row->id);
}
echo $data->num_rows.'rows inserted';
}
catch (Exception $e)
{
echo $e->getMessage();
// Stop method execution with return, or use exit
return;
}