Validation is not working. All the form fields are coming dynamically. It depends on the user how many fields he chooses.If he chooses 2 and it will display 2 fields in the view. If select 3 then it will display 3 fields and so on.I have more than 30 fields
I set 3 arrays(for testing purpose I set only 3. It will be total no of fields ) in my form validation page. If I remove the last array than validation is working because I am getting only 2 fields in the view. I am not able to use the more than 2 array in my form validation page.
Is it mandatory to require the number of fields in view is equal to a number of sets of rules array in form validation?
View
This is my dynamic view page
<?php
echo form_open('formbuilder_control/enxample_from_view');
foreach ($data as $key) {// I am getting output
$exp_fields_name=$key->fields_name;
$exp_fields_type=$key->fields_type;
$exp_form_elements=$key->form_elements;
$abc=explode(',',$exp_form_elements);
foreach ($abc as $value) {
if ($exp_fields_name == $value) {?>
<div class="form-group row label-capitals">
<label class="col-sm-5 col-form-label"><?php echo $exp_fields_name;?></label>
<div class="col-sm-7">
<input type="<?php echo $exp_fields_type;?>" name="<?php echo $exp_fields_name;?>" placeholder="<?php echo $value;?>" class="form-control" />
<?php echo form_error($exp_fields_name); ?>
</div>
</div>
<?php
}}}?>
<div class="form-buttons-w btn_strip">
<input type="submit" name="submit" value="Save" class="btn btn-primary margin-10">
</div>
<?php echo form_close(); ?>
Form_validation.php
$config = array(
'test'=>array(
array('field' =>'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array('field' => 'lastname',
'label' => 'lastname',
'rules' => 'required'
),
array('field' => 'middlename',
'label' => 'middlename',
'rules' => 'required'
)
),
);
Controller
public function test()
{
if($this->form_validation->run('test') == TRUE)
{
echo "working";
}
$this->load->view('test1');
}
Of course it will fail. Your validation rules define a 'middlename' field as required, and that field doesn't even exist in the form.
A missing field cannot satisfy a required rule.
It is possible to have flexible sets of rules with a minimum of code. Consider this form_validation.php example
<?php
$first_last = array(
array('field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array('field' => 'lastname',
'label' => 'lastname',
'rules' => 'required'
),
);
$middle_name = array(
array('field' => 'middlename',
'label' => 'middlename',
'rules' => 'required'
)
);
$config = array(
'fullname' => array_merge($first_last, $middle_name), //first, middle and last name fields
'shortname' => $first_last, //only first and last name fields
);
This provides two different sets of fields for use with form_validation->run().
For example: On a form using first, middle and last name fields
if($this->form_validation->run('fullname'))
{
...
Or, when the form contains only the first and last name fields
if($this->form_validation->run('shortname'))
{
...
As others have mentioned, you are requiring a field that does not exist. You either need to:
Add a field in your view with the name middlename
Remove the validation rule that requires a field middlename to exist
Not contributing to your issue, but in a usability aspect, you likely want to change the label in your lastname and middlename rules to make them more user friendly.
$config = array('test'=>array(
array('field' =>'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array('field' => 'lastname',
'label' => 'lastname',
'rules' => 'required'
),
array('field' => 'middlename',
'label' => 'middlename',
'rules' => 'required'
)
),
);
Also, the documentation has other helpful tips for different custom rules if you're not trying to require the middlename but want to sanitize or validate its format prior to insertion into a database.
https://www.codeigniter.com/userguide3/libraries/form_validation.html#form-validation-tutorial
Well, as you want to have one set of validation rules and you have two different forms to validate, you can do it using very nice option with Codeigniter's validation callback function.
I am going to post a simple example here:
Your view file:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo form_open('formbuilder_control/test');?>
<input type="text" name="firstname">
<input type="hidden" name="which_form" value="first_form">
<?php echo form_error('firstname'); ?>
<input type="text" name="lastname">
<?php echo form_error('lastname'); ?>
<input type="submit" name="submit" value="submit">
<?php echo form_close(); ?>
<?php echo form_open('formbuilder_control/test');?>
<input type="text" name="firstname">
<input type="hidden" name="which_form" value="second_form">
<?php echo form_error('firstname'); ?>
<input type="text" name="lastname">
<?php echo form_error('lastname'); ?>
<input type="text" name="middlename">
<?php echo form_error('middlename'); ?>
<input type="submit" name="submit" value="submit">
<?php echo form_close(); ?>
</body>
</html>
<?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('which_form') == "second_form" && !$this->input->post('middlename'))
{
$this->form_validation->set_message('middlename', 'Middle name is required!');
return FALSE;
}
return TRUE;
}
}
From above example you can see required_inputs function is just like a normal function, where you can write any php code.
So what I would advice is, have one hidden field in both of the forms, jus to check which form got submitted, and then set callback function for middlename validation rule and in that function, check which form is submitted by user, and based on it, return TRUE or FALSE.
I hope this will get you the whole idea what you can do.
You just need to add a hidden field with different value in each the forms and check the value in callback function to decide whether you should apply the third validation rule or not.
Related
I am creating a form in codeigniter where user needs to fill data and submit it, but after submission of form if there are any errors the user gets redirected back to the form, however at this stage the values that he had entered should stay in the form.
I am getting the flashdata error but the values are not getting retained in the form. I tried to use set_value but just getting blank form in return. Can any one please point out the error
View
<?php echo form_open_multipart('student/data/'.$student->id); ?>
<p><?php echo $this->session->flashdata('req_msg'); ?></p>
<?php
$data = array(
'type' => 'text',
'name' => 'name',
'placeholder' => 'Full Name',
'class' => 'form-control',
'id' => 'form-first-name',
'value' => set_value('name')
);
?>
<?php echo form_input($data); ?>
<?php
$data = array(
'type'=>'tel',
'pattern'=>'^\d{10}$',
'name' => 'contactno',
'placeholder' => 'Enter 10 digit Contact No',
'class' => ' form-control',
'required' => 'required',
'id' => 'form-first-name',
'value' => set_value('contactno')
);
?>
<?php echo form_input($data); ?>
<div class="form-group">
<?php
$data = array(
'type' => 'submit',
'class' => 'btn btn-primary',
'name' => 'submit',
'content' => 'Upload',
'id' => 'btn-submit'
);
echo form_button($data);
?>
</div>
<?php echo form_close(); ?>
Controller
$this->form_validation->set_rules('contactno', 'Contact Number', 'trim|is_unique[student.contactno]');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('req_msg', 'Contact number already exists');
redirect('student/data/'.$studentid);
}
Your view file's code is absolutely correct. You only need to few modifications in your controller's method.
There few key points you need to know before implementing solution in your code:
Redirect only when your validation rules passes successfully and your motive behind taking user's input is done
When your validation rules does not pass then load your view instead redirecting it
Put form_error(FIELD_NAME) along with each input to show validation error
Below is the example of action:
public function add()
{
$this->form_validation->set_rules('contactno', 'Contact Number', 'trim|is_unique[student.contactno]');
if ($this->form_validation->run() !== FALSE) {
// Your database or model function calling will be coded here and make sure it returns boolean value
if ($isTrue) {
$this->session->set_flashdata('req_msg', 'Congrats! You have successfully submitted data');
redirect('student/data/'.$studentid);
}else{
// Handle error logs here
}
}
$this->load->view('your_view', $this->view_data);
}
This is the complete solution. I am sure you will get all the values set in form field in case of validation rule fails.
Let me know if you face any issue.
The problem is caused because you redirect after FALSE form_validation. You must load the view there like below :
if ($this->form_validation->run() == FALSE) {
//your code
$this->load->view('your_view', $this->view_data);
}
In your view you have to use set_value() in your inputs.
More info # documentation
I try to create Update Form with form helper CI. everything Work if on form_input. But, when id on form_hidden, it return NULL. this the script
on View
$hidden = array('name'=>'id_hidden','value'=>$datacompany[0]->id);
echo form_hidden($hidden); //I have edited
On Controller
function edit_company()
{
if(isset($_POST['EDIT']))
{
print_r($_POST);//return All value
$isi = array(
'id' =>$this->input->post('id_hidden'),//return null
'nip' =>$this->input->post('nip'),//return value
'nama' =>$this->input->post('nama'), //return value
'golongan' =>$this->input->post('golongan') //return value
);
echo $isi['id']; //the result id is null
}//end if
}//end Function
That Id I need for using on model. How Can I Fix That?
How to Catch ID from form_hidden?
I'm very appreciated Your Answer
thanks
While using my first comment will let you debug it in 3 seconds, Here's the answer :)
You're using the form_hidden in the wrong way.
An array in the form_hidden turns to this (from the docs)
$data = array(
'name' => 'John Doe',
'email' => 'john#example.com',
'url' => 'http://example.com'
);
echo form_hidden($data);
// Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john#example.com" />
<input type="hidden" name="url" value="http://example.com" />
As you see, the 'keys' of the array turn to the names of the fields.
The value is the 'value' of the array. so in your example, you're making two hidden fields.
<input type="hidden" name="name" value="id_hidden">
<input type="hidden" name="value" value="$datacompany[0]->id">
You need to define like this a hidden field in CI:
$hidden = array('id_hidden',$datacompany[0]->id); // a name and value pair for a single instance.
echo form_hidden($hidden);
$hidden = array('id_hidden' => $datacompany[0]->id);
echo form_hidden($hidden);
I think this will fulfill your need.
Or if you want other attributes... Try with this..
$data = array(
'name' => 'username',
'id' => 'username',
'value' => 'johndoe',
'maxlength' => '100',
'type' => 'hidden',
'size' => '50',
'style' => 'width:50%',
);
echo form_input($data);
Depend on your need.
I am a new cake php developer.I am trying to insert multiple record but i cant.My table Structure is given below:
Table Name :
agents
==============================================
id | Contact | Name | email_add | Address
==============================================
Controller Code :
public function send_money()
{
$this->layout='agent';
$this->Agent->create();
$this->Agent->set($this->data);
if(empty($this->data) == false)
{
if($this->Agent->save($this->data))
{
$this->Session->setFlash('Information Added Successfully.');
$this->redirect('send_money');
}
}
else
{
$this->set('errors', $this->Agent->invalidFields());
}
}
Model Code Is :
<?php
App::uses('AppModel', 'Model');
/**
* Admin Login Model
*
*/
class Agent extends AppModel
{
public $name='Agent';
public $usetables='agents';
public $validate = array(
'contact' => array(
'contact_not_empty' => array(
'rule' => 'notEmpty',
'message' => 'Please Give Contact No',
'last' => true
),
),
'name' =>array(
'rule' => 'notEmpty', // or: array('ruleName', 'param1', 'param2' ...)
'allowEmpty' => false,
'message' => 'Please Enter Name.'
),
'email_add' => array(
'email_add' => array(
'rule' => 'email',
'allowEmpty' => true,
'message' => 'Please Enter Valid Email',
'last' => true
)),
);
}
?>
Its not possible to insert records with this code.What should I do?
Let me explain everything.
First of all your html form must be looks like following.
<?php echo $this->Form->create('User'); ?>
<tr>
<td>
<?php
echo $this->Form->input('User.0.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.1.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
<?php
echo $this->Form->input('User.2.address',array
(
'div' => null,
'label' => false,
'class' => 'span required'
));
?>
</td>
<td>
<input type="submit" value="Add" >
</td>
</tr>
<?php echo $this->Form->end(); ?>
As you can see to save many record at same time using cakephp you must define it as above it will parse input fields as array this is cakephp convention.
I mean User.0.address for first array element
User.1.address for second array element
User.2.address for third array element and so on.
Now.
In Controller file.
<?php
function add()
{
$this->User->saveAll($this->data['User']);
}
And yes here you are done saving multiple record at same time.
I just gave you how cakephp works all you need to do is set above hint as per your need.
Best of luck...
Cheers...
Feel Free to ask... :)
Try this saveall() in your query except save, hope this helps
if($this->Agent->saveall($this->data))
Let me know if it work.
I think this
php echo $this->Form->create('Agents', array('action' => 'send_money'));?>
should be replaced with
php echo $this->Form->create('Agent', array('action' => 'send_money'));?>
and use saveall() in place of save.
I'm using this datamapper http://datamapper.wanwizard.eu
problem is datamapper have validation methods similar with codeigniter form validation.but not as same.
An example, a model admins model validation array:
public $validation = array(
'username' => array(
'rules' => array('unique', 'required', 'trim', 'max_length' => 60, 'min_length' => 3),
'label' => 'User'
),
'password' => array(
'rules' => array('required', 'trim', 'encrypt', 'min_length' => 6),
'label' => 'Password'
)
);
but form validation array must be like that:
public $form_validation = array(
array(
'field' => 'username',
'label' => 'User',
'rules' => 'unique|required|trim|max_length[60]|min_length[3]'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|encrypt|min_length[6]'
)
);
I don't want to make two manual validation for new admin adding (first form validation, after datamapper validation). I think there is a way to make this with just one manual validation.
sorry my bad English, I hope you understand. Thanks in advance.
Using the Datamapper's validation alone should be enough, without the CI's form library.
When you try to save the model, the save() method will return a true or false depending on if the save was successful. If it isn't the model's error property should be filled with the error messages generated for the validation that failed. The messages can be loaded from language files with keys named appropriately, also the codeigniter's form validation library's form_validaton_lang.php is loaded too.
In your controller you could make use of them like this:
Class TheController extends CI_Controller {
function save() {
// get the model object somehow
// ...
// update attributes
$model->prop0 = $this->input->post('prop0');
$model->prop1 = $this->input->post('prop1');
// try to save it
if ($model->save()) {
// save successful
redirect(...);
} else {
// save failed load form again, with the model
$this->load->view('path/to/the/form', array('model' => $model));
}
}
}
The view could work like this:
<form method="post" action="...">
<label>prop0</label>
<input type="text" name="prop0" value="<?php print $model->prop0?> ">
<?php if (!empty($model->error->prop0)):?>
<div class="error"><?php print $model->error->prop1; ?></div>
<?php endif; ?>
<label>prop1</label>
<input type="text" name="prop1" value="<?php print $model->prop1?> ">
<?php if (!empty($model->error->prop0)):?>
<div class="error"><?php print $model->error->prop1; ?></div>
<?php endif; ?>
<buton type="submit">go</button>
</form>
The same form can be used when no previous model exists in the database, just create an empty instance of the model you need, and pass it to the form.
I am trying to make an edit page where the form fields are populated from the database. I'm trying to get it working by just setting some random text, but I'm having trouble making it show.
I have the following in my controller:
public function edit($item_id) {
$this->data['title'] = "Edit Item";
$this->data['item_title'] = array(
'name' => 'item_title',
'id' => 'item_title',
'type' => 'text',
'value' => 'a title',
);
$this->data['url_slug'] = array(
'name' => 'url_slug',
'id' => 'url_slug',
'type' => 'text',
'value' => 'some-url-slug',
);
$this->template->build('admin/item/form', $this->data);
}
This is my view:
<?php echo form_open('admin/item/update_item', array('id' => 'item_form')); ?>
<input type="text" name="item_title" value="<?php echo set_value('item_title'); ?>" id="item_title" placeholder="Enter a title..."/>
<input type="text" name="url_slug" value="<?php echo set_value('url_slug'); ?>" id="url_slug" placeholder="url-slug-of-the-item"/>
When I go the /edit/id page, the placeholder is still showing and the value is blank. Why is not setting? It works fine when I use it for form validation.
I'm still new to codeigniter, so forgive my ignorance.
Can't you simply use the following?
<input type="text" name="item_title" value="<?= $item_title['value'] ?>" id="item_title" placeholder="Enter a title..."/>
Note: This would be valid for fuelphp; not 100% sure about codeigniter.
I ended up ditching the array and just doing $this->data['item_title'] = 'some title'; in the controller, and in the the view, set_value actually accepts a 2nd parameter, like this:
<?php echo set_value('item_title', $item_title); ?>
This does the trick, although I do get warnings if the variable doesn't exist, so I need to declare them all.
I ended up ditching the array and just doing $data['fullName'] = 'some title'; in the controller, and in the the view, set_value actually accepts a 2nd parameter, like this:
<?php
if(!isset($fullname)) {
$fullname = set_value('fullName');
}
echo form_open(base_url() . "broker/practice_send.html");
echo form_label("Name", "name");
$data = array(
'name' => 'fullName',
'id' => 'name',
'value' => set_value('fullName', $fullname)
);
echo form_input($data);
?>