Im carrying out some form validation with codeigniter using a custom validation callback.
$this->form_validation->set_rules('testPost', 'test', 'callback_myTest');
The callback runs in a model and works as expected if the return value is TRUE or FALSE. However the docs also say you can return a string of your choice.
For example if I have a date which is validated, but then in the same function the format of the date is changed how would I return and retrieve this new formatted value back in my controller?
Thanks for reading and appreiate the help.
I'm not entirely sure I got what you were asking, but here's an attempt.
You could define a function within the constructor that serves as the callback, and from within that function use your model. Something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controllername extends CI_Controller {
private $processedValue;
public function index()
{
$this->form_validation->set_rules('testpost','test','callback');
if ($this->form_validation->run()) {
//validation successful
echo $this->processedValue; //outputs the value returned by the model
} else {
//validation failed
}
}
private function callback($input)
{
$this->load->model('yourmodel');
$return = $this->yourmodel->doStuff($input);
//now you have the user's input in $input
// and the returned value in $return
//do some checks and return true/false
$this->processedValue = $return;
}
}
public function myTest($data){ // as the callback made by "callback_myTest"
// Do your stuff here
if(condition failed)
{
$this->form_validation->set_message('myTest', "Your string message");
return false;
}
else
{
return true;
}
}
Please try this one.
I looked at function _execute in file Form_validation of codeigniter. It sets var $_field_data to the result of callback gets(If the result is not boolean). There is another function "set_value". Use it with the parameter which is name of your field e.g. set_value('testPost') and see if you can get the result.
The way Tank_Auth does this in a controller is like so
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
// validation ok
$this->form_validation->set_value('login')
}
Using the set_value method of form_validation is undocumented however I believe this is how they get the processed value of login after it has been trimmed and cleaned.
I don't really like the idea of having to setup a new variable to store this value directly from the custom validation function.
edit: sorry, misunderstood the question. Use a custom callback, perhaps. Or use the php $_POST collection (skipping codeigniter)...apologies haven't tested, but I hope someone can build on this...
eg:
function _is_startdate_first($str)
{
$str= do something to $str;
or
$_POST['myinput'} = do something to $str;
}
================
This is how I rename my custom callbacks:
$this->form_validation->set_message('_is_startdate_first', 'The start date must be first');
.....
Separately, here's the callback function:
function _is_startdate_first($str)
{
$startdate = new DateTime($this->input->post('startdate'), new DateTimeZone($this->tank_auth->timezone()));
$enddate = new DateTime($this->input->post('enddate'), new DateTimeZone($this->tank_auth->timezone()));
if ($startdate>$enddate) {
return false;
} else {
return true;
}
}
Related
So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)
By some reason form validation doesn't call callback function which I set in the rules.
It is rules sets
if( ! empty($_POST))
{
ci()->form_validation->set_rules('login', 'Username', 'trim|required');
ci()->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_email');
if (ci()->form_validation->run() == TRUE)
{
}
}
and a function
public function check_email($str)
{
ci()->load->model(array('secure_model', 'admin/members_model'));
$o['username'] = ci()->input->post('login');
$o['email'] = ci()->input->post('email');
$m = $this->_model->get_row($o);
if ( ! $m)
{
$this->form_validation->set_message('check_email', lang('unlock_incorrect_login'));
return FALSE;
}
else
{
return FALSE;
}
}
I set FALSE twice to see if it call callback function but it doesn't display error message. So I suppose CI doesn't try to call it. What is wrong?
In your check_email() function, you're using $this->form_validation instead of ci()->. I'm not sure why you're using ci() instead of the standard CI way of using $this but that's the part in your code which seems off compared to the rest.
Lets see the action (form is based on model)
$this->form->bind ($request->getParameter('task'));
if ($this->form->isValid())
{
// cakk
}
This all works good, its not valid when its really not valid etc.
But I want to edit some fields, for example a date must be always set to now. Or a password must be encoded. How can I do this?
You can override the doSave() method in the form .. something like this :
public function doSave($con = null)
{
$this->values['form field'] = 'newvalue';
parent::doSave($con);
}
$this->values is an array containing the values on the form.
Update
You could use a post validator .. like this (again in the form class) :
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'methodName')))
);
public function methodName($validator, $values)
{
// check / change what you need to
$values['fieldname'] = 'new value';
// return values
return $values;
}
Im using CodeIgniter to write a site ... I understand $_GET requests are now used like so www.website.com/function/value .. and in the controller getting a url segment is written like so:
$userId = $this->uri->segment(3, 0);
Im just wondering, when a controller loads, i want to check if there is any uri segments, if there is then push to one view, else if there isnt a uri segment push to another.
Is that possible?
cheers.
You can use your controller arguments for that too.
When accessing /user/profile/1 your controller named User will call the method profile() and pass the number 1 as the first argument to your method. Like so:
class User extends CI_Controller {
{
public function index()
{
$this->load->view("user_index");
}
public function profile ( $userId = null )
{
if( (int)$userId > 0 )
$this->load->view("user_profile");
else
$this->load->view("another_view");
}
}
This is a very basic sample and I'm just trying to show the idea.
Seems like your asking two questions...
First, to check if the request is get
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
echo "GET";
}
else
{
//do something not get
echo "NOT GET";
}
}
The next question seemed to be checking uri segments
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
//echo "GET";
if($this->uri->segment(3)) //is true as is not empty
{
echo $this->uri->segment(3);
}
else
{
echo "I am nothing without my URI Segment";
}
}
else
{
//do something not get
echo "NOT GET";
}
}
As I understand you can use PHP default value.
function myFunction($var1 = NULL) {... if($var1 === NULL) ...}
Now if you do not pass the param you will get the NULL value.
I am still not using version 2 of codeigniter but this framework do not accept get requests; unless you mess with the configuration. Theres a function $this->input->get('myGet') you should look around at de the codeigniter.com/user_guide
i am newbie in CodeIgniter...and i am trying to do form validation for array input...
the array name is pages[].
and i wrote:
$this->form_validation->set_rules('pages[]','','required');
if i use that:
$this->form_validation->set_message('required', 'you not selected pages.');
it will not change the other "required" validation input params?
So how can i set error message only for one validation?
This is my custom Form_Validation class. you can use it if you want to. put this file under your libraries directory. then you can use the set message like this:
$this->form_validation->setError(YOUR_INPUT_NAME, THE_MESSAGE);
ex: $this->form_validation->setError('email', 'Invalid email');
--
class MY_Form_validation extends CI_Form_validation {
public function set_error($field, $pesan_error){
$this->_field_data[$field]['error'] = $pesan_error;
}
public function get_error($field){
return $this->_field_data[$field]["error"];
}
public function get_all_error(){
// return $this->_field_data[$field]["error"];
$fields = $this->_field_data;
$pesan = "";
foreach($fields as $field ) {
if($field["error"]) {
$pesan .= "<p>$field[error]</p>";
}
}
return $pesan;
}
}
It doesn't work like you stated, you should read this section of the user guide more carefully.
I'm not sure I can explain better, but the first field of the set_message method doesn't refer to the type of validation but to the callback function's name, that's the function which is doing the custom validation work.
What you need to do is define your callback function (the guide has a good example), in which you iterate through your array's elements and count what's checked. If at the end of the iteration the counter is 0 you set your error message.
Hope this helps.