How do I get domPDF to display my codeigniter view correctly - codeigniter-2

I feel there is a small step that I am missing that apparently everyone on the other related questions understands.
I have created a simple CI 2 view, controller and model, shown below:
I have installed dompdf into the helpers folder like so:
applications/helpers/dompdf
applications/helpers/dompdf/dompdf_help.php
What I want to happen is when user clicks the submit button on the view page, send form data to the db, then get a pdf of that filled in form.
Between getting underdefined var errors or nothing at all, except for the data going to db, I can't see what I am missing.
Could some please guide me? What am I not getting here?
View
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test pdf</title>
</head>
<body>
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open('quicksubmit', $attributes); ?>
<p>
<label for="title">Title <span class="required">*</span></label>
<?php echo form_error('title'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Mrs' => 'Mrs',
'Miss' => 'Miss',
'Ms' => 'Ms',
'Mr' => 'Mr',
); ?>
<br /><?php echo form_dropdown('title', $options, set_value('title'))?>
</p>
<p>
<label for="first_name">First Name</label>
<?php echo form_error('first_name'); ?>
<br /><input id="first_name" type="text" name="first_name" maxlength="100" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label for="last_name">Last Name <span class="required">*</span></label>
<?php echo form_error('last_name'); ?>
<br /><input id="last_name" type="text" name="last_name" maxlength="100" value="<?php echo set_value('last_name'); ?>" />
</p>
<p>
<label for="branch">Branch</label>
<?php echo form_error('branch'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Branch 1' => 'Branch One',
'Branch 2' => 'Branch Two',
); ?>
<br /><?php echo form_dropdown('branch', $options, set_value('branch'))?>
</p>
<p>
<label for="zip">Zip</label>
<?php echo form_error('zip'); ?>
<br /><input id="zip" type="text" name="zip" maxlength="7" value="<?php echo set_value('zip'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('quicksubmit_model');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$this->pdf($output);
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/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
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf()
{
$this->load->helper(array('dompdf', 'file'));
// page info here, db calls, etc.
$html = $this->load->view('quicksubmit_view', $data, true);
pdf_create($html, 'filename');
/*or
$data = pdf_create($html, '', false);
write_file('name', $data);*/
//if you want to write it to disk and/or send it as an attachment
}
}
?>
Model
<?php
class Quicksubmit_model extends CI_Model {
function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* function SaveForm()
*
* insert form data
* #param $form_data - array
* #return Bool - TRUE or FALSE
*/
function SaveForm($form_data)
{
$this->db->insert('quicksubmit', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
}
?>
dompdf_help.php file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename.".pdf");
} else {
return $dompdf->output();
}
}
?>

you were nearly there!
It is probably better to store dompdf in the third_party folder, and it is not a code igniter helper. - see the path i store it in in the constructor. Then it is always available.
Also, it is probably better to do the 'work' of the program in the model, so this includes making PDFs etc.
don't use a ?> at the end of your code.
i modded your code to work, and verified it did work. it simply saves a file named tmp/name.pdf. I am sure you can work out the rest. i did comment out the database loader because that wasn't needed for me to test the code.
see enc.
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
//$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('file');
$this->load->model('quicksubmit_model');
global $_dompdf_show_warnings;global $_dompdf_debug;global $_DOMPDF_DEBUG_TYPES;global $_dompdf_warnings;$_dompdf_show_warnings = FALSE;
require_once(realpath(APPPATH."third_party/dompdf")."/dompdf_config.inc.php"); // remember that the constant DOMPDF_TEMP_DIR may need to be changed.
spl_autoload_register('DOMPDF_autoload');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
$this->pdf($form_data);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/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
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf($data)
{
$dompdf = new DOMPDF();
$html = $this->load->view('quicksubmit_view', $data, true);
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
write_file('tmp/name.pdf', $pdf);
}
}

Related

Ion Auth profile page

I would like a step by step tutorial on how to create a profile page for ion auth codeigniter.
When a logged in user clicks a link User profile link, it opens a user profile page and retrieves all the details of the user in a form so the user can update. I would this to be for the admin users.
Thank you :)
I ended up doing it this way :
below controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->library('ion_auth');
}
public function index() {
}
public function login() {
if ($this->input->post()) {
$this->load->library('form_validation');
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
if ($this->form_validation->run() === TRUE) {
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {
redirect('dashboard', 'refresh');
} else {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('admin/user/login', 'refresh');
}
}
}
$data['main_content'] = 'admin/login';
$this->load->view('includes/template', $data);
}
public function logout() {
$this->ion_auth->logout();
redirect('admin/user/login', 'refresh');
}
public function profile() {
$user = $this->ion_auth->user()->row();
//print_r($user);
$this->data['user'] = $user;
//var_dump($user);
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'trim');
$this->form_validation->set_rules('last_name', 'Last name', 'trim');
$this->form_validation->set_rules('company', 'Company', 'trim');
$this->form_validation->set_rules('phone', 'Phone', 'trim');
if ($this->form_validation->run() === FALSE) {
$this->load->view('admin/edit_profile', $this->data);
} else {
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone')
);
if (strlen($this->input->post('password')) >= 6)
$new_data['password'] = $this->input->post('password');
$this->ion_auth->update($user->id, $data);
redirect('dashboard', 'refresh');
}
//$this->load->view('admin/edit_profile', $data);
}
}
then the view :
<h1><?php echo lang('edit_user_heading');?></h1>
<p>
<?php echo lang('edit_user_fname_label', 'first_name');?> <br />
<?php echo form_input($first_name);?>
</p>
<p>
<?php echo lang('edit_user_lname_label', 'last_name');?> <br />
<?php echo form_input($last_name);?>
</p>
<p>
<?php echo lang('edit_user_company_label', 'company');?> <br />
<?php echo form_input($company);?>
</p>
<p>
<?php echo lang('edit_user_phone_label', 'phone');?> <br />
<?php echo form_input($phone);?>
</p>
<p>
<?php echo lang('edit_user_password_label', 'password');?> <br />
<?php echo form_input($password);?>
</p>
<p>
<?php echo lang('edit_user_password_confirm_label', 'password_confirm');?><br />
<?php echo form_input($password_confirm);?>
</p>
<?php if ($this->ion_auth->is_admin()): ?>
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php foreach ($groups as $group):?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo htmlspecialchars($group['name'],ENT_QUOTES,'UTF-8');?>
</label>
<?php endforeach?>
<?php endif ?>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<p><?php echo form_submit('submit', lang('edit_user_submit_btn'));?></p>

Saving data from a drop down list in CodeIgniter

I created a menu page where it has a drop down menu with a list of menus from the database and it also has a textbox to enter new menus.
The problem I'm having is that I can't seem to figure out how to save my dropdown. So for example I have a menu called "About Us" in the drop down list and I want to create a new menu called "Team", and "Team" is a child of "About Us"
So in my table I would have something like this
id | parent | title
------------------------
1 | NULL | About Us
2 | 1 | Team
Menu Controller
function get_data_from_post()
{
$data['title'] = $this->input->post('title', TRUE);
$data['parent'] = $this->input->post('parent', TRUE);
if(!isset($data)){
$data = '';
}
return $data;
}
function get_data_from_db($update_id)
{
$query = $this->get_where($update_id);
foreach($query->result() as $row){
$data['title'] = $row->title;
$data['parent'] = $row->parent;
}
return $data;
}
function create()
{
$update_id = $this->uri->segment(3);
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//person has submitted the form
$data = $this->get_data_from_post();
}else{
if(is_numeric($update_id)){
$data = $this->get_data_from_db($update_id);
}
}
if(!isset($data)){
$data = $this->get_data_from_post();
}
//$titles = array();
$query = $this->get('title');
foreach($query->result() as $row){
$titles[] = $row->title;
}
$data['titles'] = $titles;
$data['update_id'] = $update_id;
$data['view_file'] = "create";
$this->load->module('templates');
$this->templates->admin_template($data);
}
function submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
if($this->form_validation->run($this) == FALSE){
$this->create();
}else{
$data = $this->get_data_from_post();
$update_id = $this->uri->segment(3);
if(is_numeric($update_id)){
$this->_update($update_id, $data);
}else{
$this->_insert($data);
}
redirect('menus/manage');
}
}
create.php view
<div class="row">
<div class="col-md-12">
<h2>Create Menus</h2>
<h5>Welcome Jhon Deo , Need to make dynamic. </h5>
</div>
</div>
<hr />
<?php
echo validation_errors("<p style='color: red;'>", "</p>");
echo form_open('menus/submit/'.$update_id);
?>
<div class="row">
<div class="col-md-12">
<form role="form">
<div class="form-group">
<select name="menus">
<?php
foreach($titles as $title){
echo "<option value=".$title.">".$title."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Title</label>
<!-- <input class="form-control" /> -->
<?php
$data = array(
'name' => 'title',
'id' => 'title',
'value' => $title,
'class' => 'form-control',
);
echo form_input($data);
?>
</div>
<?php
$data = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-success',
'style' => 'width: 100%',
);
echo form_submit($data);
?>
</form>
</div>
</div>
<?php
echo form_close();
?>
UPDATE:
this is what I have when I print_r($titles)
Array
(
[0] => About Us
[1] => Home
)
If there is anything you don't understand or if you need me to give more information please let me know.
You should have declared a model. From there, you can create a function that will save the values in the database that you initialize via controller. You should utilize the MVC pattern of it. CodeIgniter has a great documentation to read about what I am pointing out.. https://codeigniter.com/user_guide/overview/mvc.html?highlight=model

Codeigniter: Not inserting data in table

Update: It is solved ..
For some reason, the data is not getting inserted into the table. It is however being posted from the form as I could see with var dump, but further than that, won't do. So, here are the 3 modules. It is a very simple test scheme: Just a form with two fields, you press Submit and should be inserted. (I can do all that in ordinary PHP with one page, but, the MVC frameworks are a nightmare in this regard, you write about 30 times more code than you would need in procedural.
<?php
class Inserting_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Inserting_model');
}
public function index ()
{
$this->load->view('inserting_view');
}
// Controller
public function insert()
{
$data = array(
'username' => $this->input->post('username', TRUE),
'password' => sha1($this->input->post('password', TRUE)
));
var_dump($data); // We do get the data posted
exit;
$this->Inserting_model->insertdata($data); // this should forward them to the Model
}
}
?>
==============
MODEL
<?php
class Inserting_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
}
public function insertdata($data)
{
$this->db->insert('users', $data);
}
}
?>
========
VIEW
<div id="inserting_form">
<?php echo form_open('index.php/Inserting_controller/insert/'); ?>
<ul>
<li>
<label>Username</label>
<div><?php echo form_input(array('id' => 'username', 'name' => 'username')); ?></div>
</li>
<li>
<label>Password</label>
<div><?php echo form_password(array('id' => 'password', 'name' => 'password')); ?></div>
</li>
<li><?php echo validation_errors();?></li>
<li><?php echo form_submit(array('name' =>'submit'),'Insert');?> </li>
</ul>
<?php echo form_close(); ?>
</div>
Blushing :/
On writing the debugging code, I forgot to delete the exit; thus, the program exited right after that ....

Ajax form validation in codeigniter

hellp guys,
I've been working on ajax recently, and I have a problem in using it with codeigniter form validation library. I used the example that tool generate in the function http://formtorch.geekhut.org/.
Now, ajax works perfectly and return data correctly when I use json_encode() function with dummy data, but validation in the example uses validation library instead of form_validation library, which seems to be older version.
For that, validation didn't work with ajax in that example, specifically $this->form_validation->run() function makes ajax return no result even if I echo dummy data using json_encode() in the beginning of create_course().
so what's wrong with validation with ajax, and explain to me how data sent by ajax received by the controller.
so this is my code:
function create_course()
{
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
// .. etc
if ($this->form_validation->run()) {
// validation ok
$data['course_code'] = $this->form_validation->set_value('course_code');
$data['name'] = $this->form_validation->set_value('name');
// ... etc
if ($this->models_facade->create_course($user_id,$data)) { // success
$data = array( 'profile_change' => $this->lang->line('profile_change'));
} else { // fail
$data = array( 'profile_change_error' => $this->lang->line('profile_change_error'));
}
}
else
{
$data = array(
'course_code' => $this->form_validation->course_code_error,
'name' => $this->form_validation->name_error
);
}
echo json_encode($data);
}
and this is the Jquery Ajax function
   $(function(){
$("#submit").click(function(){
var course_code = $("#course_code").val();
var name = $("#name").val();
// etc
$.post("<?php echo base_url() ?>home/create_course", course_code:course_code, name:name},
function(data){
function(data){
alert(data.data);
$("#course_code_error").html(data.course_code);
$("#name_error").html(data.name);
},'json');
});
return false;
});
   
Rather than printing out via "this->form_validation->xxxx_error" you can utilize Form Helper method "form_error()" to call the error messages.
So you can do something like..
$data = array(
'course_code' => form_error('course_code'),
'name' => form_error('name')
);
You might also consider setting the output content type header for JSON data.
$this->output->set_content_type('application/json');
echo json_encode($data);
What version of Codeigniter are you using? Did you remember to load the validation library in your construct?
$this->load->library('form_validation');
If you're making an ajax request you can use the validation_errors().
When the validation run it'll populate the array of error messages.
Here an exemple :
// Set your rules
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
if ($this->form_validation->run()) {
//happy happy time
}
else {
//well now i'm sad...
//Important to turn that off if it's on
$this->output->enable_profiler(false);
$this->output->set_status_header('500');
$this->output->set_content_type('application/json');
echo json_encode(array(
'error_msg' => validation_errors(),
));
}
And then on your client-side you can use the response like that :
error:function(data) {
$("your-error-input-selector").html('').append(data.responseJSON.msg);
}
Hope i helped even if i'm 2 year late.
P.S Sorry for my broken english.
****//view-path [application/views/myviews/myview2.php]****
<script src="<?php echo base_url('/jquery-1.9.1.min.js');?>"></script>
<script>
$(document).ready(function() {
$("#frm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: $('#frm').attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
data = JSON.parse(data);
if(data.st == 0)
{
$( ".error-message" ).remove();
var data1 = JSON.parse(data.msg);
$('form :input').each(function(){
var elementName = $(this).attr('name');
var message = data1[elementName];
if(message){
var element = $('<div>' + message + '</div>')
.attr({
'class' : 'error-message'
})
.css ({
display: 'none'
});
$(this).before(element);
$(element).fadeIn();
}
});
}
if(data.st == 1)
{
$('#validation-error').html(data.msg);
$( ".error-message" ).remove();
}
},
error: function(){}
});
}));
});
</script>
<style>
.error-message{color:red;}
</style>
<?php echo form_open_multipart('ajaxcontroller/index', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Profile Pic</h5>
<input type="file" name="image[]" value="" multiple=""/>
<div><input type="submit" value="Submit" /></div>
</form>
**//controller--[application/controllers/ajaxcontroller.php]****
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajaxcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_POST)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if (empty($_FILES['image']['name'][0])) {
$this->form_validation->set_rules('image[]', 'File', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$errors = $this->form_validation->error_array(); //function in library : My_Form_validation
echo json_encode(array('st'=>0, 'msg' => json_encode($errors)));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
if(is_array($_FILES)) {
foreach ($_FILES['image']['name'] as $name => $value){
if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) {
$sourcePath = $_FILES['image']['tmp_name'][$name];
$targetPath = "images/".$_FILES['image']['name'][$name];
if(move_uploaded_file($sourcePath,$targetPath)) {
}
}
}
}
echo json_encode(array('st'=>1, 'msg' => 'Successfully Submiited'));
}
}
else
{
$this->load->view('myviews/myview2');
}
}
}
**//library file -- path will be [application/libraries/MY_Form_validation.php]**
<?php
/**
*
* Enter description here ...
* #return CI_Controller
*/
class MY_Form_validation extends CI_Form_validation
{
public function error_array()
{
return $this->_error_array;
}
}

Form_validation isn’t using rules from config file (CodeIgniter 2)

My form validation isn’t using the rules in a config file in CodeIgniter 2. I’m accessing the form at /admin/people/add and /admin/people/edit/id and submitting to /admin/people/save. When I submit the add form it just reloads add without reporting any validation errors (my form views will display validation errors if $this->form_validation->_error_array is not empty; this is working on my login form). When I submit the edit form I get a 404 error at /admin/people/save even though that URI works when I initially go to the edit page. I'm loading the form validation library in the constructor.
application/config/form_validation.php:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'people/save' => array(
array(
'field' => 'first_name',
'label' => 'first name',
'rules' => 'trim|required'
)
) // people/save
);
/* End of file form_validation.php */
/* Location: /application/config/form_validation.php */
application/controllers/admin/people.php:
public function add() {
$fields = $this->db->list_fields('people');
/* set_defaults makes an object with null values for the fields in the database */
$person = $this->form_validation->set_defaults($fields);
$data = array(
'action' => 'add',
'person' => $person,
'button_text' => 'Add Person'
);
$data['page_type'] = 'form';
$this->layouts->set_title('Add a Person');
$this->layouts->view('people/add_edit_person_form',$data);
} // add
public function save(){
if($this->form_validation->run('people/save') == FALSE){
if(is_numeric($this->input->post('person_id'))){
$this->edit();
} else {
$this->add();
}
} else {
redirect('people'); // test to see if it's passing validation
}
} // save
application/views/add_edit_person_form.php:
<?php
$attributes = array(
'class' => 'block',
'id' => 'add_edit_person'
);
echo form_open('admin/people/save');
?>
<div class="required<?php echo form_error('first_name')?' error':'';?>">
<label for="first_name">First name:</label>
<input name="first_name" id="first_name" type="text" value="<?php echo set_value('first_name',$person->first_name); ?>" size="75" maxlength="255" />
</div>
<input name="person_id" id="person_id" type="hidden" value="<?php echo set_value('id',$person->id); ?>" />
<button><?php echo $button_text; ?></button>
</form>
After you've defined your $config array in application/config/form_validation.php, you'll need to call the following function in order to set the rules:
$this->form_validation->set_rules($config);
Reference: Setting Rules Using an Array

Resources