I do not know how to set a callback function for the view record page in codeigniter.
I use the callback_column function and it does what I need in the grid view, but on the view record page it does not work.
I searched their site and forum and did not found anything that could help me.
My code looks like:
$zeus = new grocery_CRUD();
$zeus->set_theme('bootstrap');
// $zeus->set_language('romanian');
$zeus->set_table('programari');
$zeus->columns(array('id_client', 'id_sala', 'denumire', 'numar_persoane', 'observatii'));
$zeus->callback_column('id_sala',array($this,'_test_function'));
$cod = $zeus->render();
$this->_afiseaza_panou($cod);
public function _test_function($row, $value)
{
return '0';
}
write this lines in \libraries\Grocery_CRUD.php
at line number 3530
protected $callback_read_field = array();
than put this function after constructor call
public function callback_read_field($field, $callback = null)
{
$this->callback_read_field[$field] = $callback;
return $this;
}
//Now update this function to manage the field outputs using callbacks if they are defined for the same
protected function get_read_input_fields($field_values = null)
{
$read_fields = $this->get_read_fields();
$this->field_types = null;
$this->required_fields = null;
$read_inputs = array();
foreach ($read_fields as $field) {
if (!empty($this->change_field_type)
&& isset($this->change_field_type[$field->field_name])
&& $this->change_field_type[$field->field_name]->type == 'hidden') {
continue;
}
$this->field_type($field->field_name, 'readonly');
}
$fields = $this->get_read_fields();
$types = $this->get_field_types();
$input_fields = array();
foreach($fields as $field_num => $field)
{
$field_info = $types[$field->field_name];
if(isset($field_info->db_type) && ($field_info->db_type == 'tinyint' || ($field_info->db_type == 'int' && $field_info->db_max_length == 1))) {
$field_value = $this->get_true_false_readonly_input($field_info, $field_values->{$field->field_name});
} else {
$field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
}
if(!isset($this->callback_read_field[$field->field_name]))
{
$field_input = $this->get_field_input($field_info, $field_value);
}
else
{
$primary_key = $this->getStateInfo()->primary_key;
$field_input = $field_info;
$field_input->input = call_user_func($this->callback_read_field[$field->field_name], $field_value, $primary_key, $field_info, $field_values);
}
switch ($field_info->crud_type) {
case 'invisible':
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
case 'hidden':
$this->read_hidden_fields[] = $field_input;
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
}
$input_fields[$field->field_name] = $field_input;
}
return $input_fields;
}
than call same as other callback functions
As far as I'm aware GroceryCRUD doesn't provide callbacks or another means of overriding the default output in the view state.
The solution to customising this would be to create a custom view to which you will insert the data from your record. This way you can customise the layout and other presentation.
What you would then do is unset the default read view with:
$crud->unset_read();
And add a new action where there are details on how to do this here.
What to do with the new action is point it to a URL that you map in routes.php if necessary and handle it with a new function in your controller. You'll either have to write a model function to retrieve the data since this isn't passed from GC or you can use the action to target a callback and feed $row to it via POST or something so that the data for the record is accessible in the view. (Look at the example in the link above).
How do I get CodeIgniter to run custom rules on fields which don't have the required rule but the user left empty?
The best I can come up with is to add a space to the field if the string is empty, and then add a trim rule -- but this feels hacky.
Example rule #1
Field is required only if another field has a certain value:
// depends[another_field.some_val]
public function depends($str, $field){
list($post_key, $post_val)=explode('.', $field);
if($_POST[$post_key] == $post_val){
return $str != "";
}
return true;
}
Example rule #2
Field is required only if a regex exists on the database:
// regex[table_name.col_name.some_val]
public function regex($str, $field){
list($table, $col, $post_val)=explode('.', $field);
// Grab the regex
$regex = $this->CI ->db
->limit(1)
->select($col)
->where($post_val, $_POST[$post_val])
->get($table)
->row($col);
return preg_match('/'.$regex.'/', $str) === 1;
}
Why is there a need of a different function for a simple task. Use if..else.
Assuming that if input1 has value equals value1, then only you have to set the required validation rule for the other input which is say input2.
View:
<form action="/controller_name/function_name/" method="POST">
<input type="text" name="input1" />
<input type="text" name="input2" />
<input type="submit" />
</form>
Controller:
class Controller_name extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
public function function_name()
{
if($this->input->is_post())
{
if($this->input->post('input1') == 'value1')
{
$this->form_validation->set_rules('input2', 'input2', 'required');
}
if ($this->form_validation->run() == FALSE)
{
// something's wrong in form!
}
else
{
// form is good, proceed!
}
}
}
}
From the code, the problem you point out is that you NEED make a field required. Well, make a kind of required field with a new rule: 'keep_checking'. This way, you force the system to check whatever you want. What I did:
A My_Form_validation class which extends system core class (so, you won't have to touch system files). NOTE: Don't forget this file goes inside of application/libraries folder
Check if the custom rule 'keep_checking' is set. That will override the behaviour of not checking the fields when 'required' rule is set (See the code below)
Last point, after extending the Form_validation class you'll have a place to put all your new custom rules you'll be using all the time, XD
class MY_Form_validation extends CI_Form_validation
{
public function __construct( $rules = array( ) ) {
parent::__construct( $rules );
}
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// If the $_POST data is an array we will run a recursive call
if (is_array($postdata))
{
foreach ($postdata as $key => $val)
{
$this->_execute($row, $rules, $val, $cycles);
$cycles++;
}
return;
}
// --------------------------------------------------------------------
// If the field is blank, but NOT required, no further tests are necessary
$callback = FALSE;
//====================================================================
// NEW ADDED RULE > 'keep_checking', will check all the rules even if
// the field is empty
//====================================================================
if ( ! in_array('required', $rules) AND is_null($postdata) AND ! in_array( 'keep_checking', $rules ) )
{
// Before we bail out, does the rule contain a callback?
if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match))
{
$callback = TRUE;
$rules = (array('1' => $match[1]));
}
else
{
return;
}
}
// --------------------------------------------------------------------
// Isset Test. Typically this rule will only apply to checkboxes.
//====================================================================
// NEW ADDED RULE > 'keep_checking', will check all the rules even if
// the field is empty
//====================================================================
if (is_null($postdata) AND $callback == FALSE && !in_array( 'keep_checking', $rules ))
{
if (in_array('isset', $rules, TRUE) OR in_array('required', $rules))
{
// Set the message type
$type = (in_array('required', $rules)) ? 'required' : 'isset';
if ( ! isset($this->_error_messages[$type]))
{
if (FALSE === ($line = $this->CI->lang->line($type)))
{
$line = 'The field was not set';
}
}
else
{
$line = $this->_error_messages[$type];
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']));
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
}
return;
}
// --------------------------------------------------------------------
// Cycle through each rule and run it
foreach ($rules As $rule)
{
$_in_array = FALSE;
// We set the $postdata variable with the current data in our master array so that
// each cycle of the loop is dealing with the processed data from the last cycle
if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata']))
{
// We shouldn't need this safety, but just in case there isn't an array index
// associated with this cycle we'll bail out
if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
{
continue;
}
$postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
$_in_array = TRUE;
}
else
{
$postdata = $this->_field_data[$row['field']]['postdata'];
}
// --------------------------------------------------------------------
// Is the rule a callback?
$callback = FALSE;
if (substr($rule, 0, 9) == 'callback_')
{
$rule = substr($rule, 9);
$callback = TRUE;
}
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if (preg_match("/(.*?)\[(.*)\]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Call the function that corresponds to the rule
if ($callback === TRUE)
{
if ( ! method_exists($this->CI, $rule))
{
continue;
}
// Run the function and grab the result
$result = $this->CI->$rule($postdata, $param);
// Re-assign the result to the master data array
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
// If the field isn't required and we just processed a callback we'll move on...
if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE)
{
continue;
}
}
else
{
if ( ! method_exists($this, $rule))
{
// If our own wrapper function doesn't exist we see if a native PHP function does.
// Users can use any native PHP function call that has one param.
if (function_exists($rule))
{
$result = $rule($postdata);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
else
{
log_message('debug', "Unable to find validation rule: ".$rule);
}
continue;
}
$result = $this->$rule($postdata, $param);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
// Did the rule test negatively? If so, grab the error.
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];
}
// Is the parameter we are inserting into the error message the name
// of another field? If so we need to grab its "field label"
if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
{
$param = $this->_translate_fieldname($this->_field_data[$param]['label']);
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
return;
}
}
}
}
UPDATE:
Checkbox line was avoiding keep checking. Just add the new line I added, and it'll work. You have to add the keep_checking rule to any field you want to check:
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
public function test()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'keep_checking|required');
$this->form_validation->set_rules('surname', 'Surname', 'keep_checking|is_numeric');
if ( $this->form_validation->run() ) {
} else {
$this->load->view('form');
}
}
}
View: form.php
<form action="test" method="post">
<?php echo validation_errors(); ?>
<p>
Name: <input name="name">
</p>
<p>
Surname: <input name="surname">
</p>
<p>
<input type="submit" value="Send">
</p>
</form>
After submit that form, you'll see as CI check all rules from the input fields. Last point, don't forget that MY_Form_validation goes inside of libraries folder
In my update methods I only wanted to submit fields that were dirty. Not all fields were required and validation was failing if one a field that needed no validation was sent as empty.
So if the user wanted to remove their phone it would be sent like phone:"" and the validation wouldn't see it if I tried to pass it like so.
if($this-put("phone")) $this->form_validation->set_rules('phone', 'Phone', 'trim');
So I had to use array_key_exist() for it to see it and pass it, even it it was empty.
if($this->put("description")) $this->form_validation->set_rules('description', 'Description', 'trim|required');
if(array_key_exists("phone", $this->input->post())) $this->form_validation->set_rules('phone', 'Phone', 'trim');
I think what you are looking for is callbacks
You can define callbacks in your rule
$this->form_validation->set_rules('field1', 'Field 1', 'trim|callback_field1_check');
$this->form_validation->set_rules('field2', 'Field 2', 'callback_field2_check');
And now you can have a function with boolean return value.
public function field1_check($input) {
if ($input != '') {
$this->field1Set = true;
}
}
public function field2_check($input) {
// do something on $input
$input = trim($input);
// awesome thing is, you get to access all the field variables of your control here
// so in some other function, you'll toggle a boolean to note that an optional field was filled
// that variable set by other validation callback, you can use here
if ($this->field1Set === true && $input == '') return false;
return true;
}
I've worked out a way to do this myself by editing system/libraries/Form_validation.php.
I changed $callback to TRUE on line 487:
$callback = TRUE;
And commented out lines 488 - 500:
if ( ! in_array('required', $rules) AND is_null($postdata))
{
// Before we bail out, does the rule contain a callback?
if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match))
{
$callback = TRUE;
$rules = (array('1' => $match[1]));
}
else
{
return;
}
}
The bounty still stands if someone can think of a solution without editing CodeIgniter's system files.
function add($id = '') {
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('title_description', 'title_description', 'trim|required');
$this->form_validation->set_rules('color', 'color', 'trim|required');
$this->form_validation->set_rules('button', 'button', 'trim|required');
//$this->form_validation->set_rules('description', 'Description', 'trim|required');
if ($this->form_validation->run() == FALSE) {
echo "Not Valid";
} else {
echo "Valid";
}
}
You can add an hidden input in the view with permanent value and test it in validates rules.
In view:
<input type="hidden" name="id_form" value="1"/>
In model or controller (it depends of your architecture)
public function validates_rules(){
$this->form_validation->set_rules('id_form', 'Title', 'callback_values_check');
...
}
public function values_check($id_form){
if($this->input->post('other_value_to_test')){
...
}
}
While using change password in Zend Form,I want to check old password and new password.Both should not be same.Is there any option in Zend Form to check the both.
Thanks in advance.
Create a Library under My and use the following:
class My_Validate_PasswordConfirmation extends Zend_Validate_Abstract
{
const NOT_MATCH = 'notMatch';
protected $_messageTemplates = array(
self::NOT_MATCH => 'Password confirmation does not match'
);
public function isValid($value, $context = null)
{
$value = (string) $value;
$this->_setValue($value);
if (is_array($context)) {
if (isset($context['password_confirm'])
&& ($value == $context['password_confirm']))
{
return true;
}
} elseif (is_string($context) && ($value == $context)) {
return true;
}
$this->_error(self::NOT_MATCH);
return false;
}
}
More Information at the : Zend Manual
Scroll down to or find :
Note: Validation Context
On the source page. Code is given right below it and so is the explanation.
Hope it helps! :)
I'm having some problems when I try upload multiples files in multiples instances of my model (tabular way).
I have a model called Files and a view that generate a form for multiple instances of that model. When I save the form without "multpart/form-data", everything works, but if I put this parameter on form and submit it, the validation shows the message that "File cannot be blank."
See my controller code bellow:
public function actionRegistration() {
$company = new Company;
$contacts = $this->getModelItens('Contact', 3);
$banks = $this->getModelItens('Bank' , 2);
$files = $this->getModelItens('File' , 2);
$company->scenario = 'create';
if($_POST['Company']) {
$company->attributes = $_POST['Company'];
$valid = $company->validate();
$valid = $this->validateModels($_POST['Contact'], $contacts) && $valid;
$valid = $this->validateModels($_POST['Bank'], $banks) && $valid;
$valid = $this->validateModels($_POST['File'], $files) && $valid;
if($valid) {
if($company->save()) {
$this->saveModels($contacts, $company->id);
$this->saveModels($banks, $company->id);
$this->saveModels($files, $company->id);
$this->redirect('/obrigado');
}
}
}
$this->render('registration', array('company' => $company, 'contacts' => $contacts, 'banks' => $banks, 'files' => $files));
}
private function getModelItens($model_name, $times, $scenario = 'create') {
$models = array();
for($i = 0; $i < $times; $i++) {
$models[$i] = new $model_name;
$models[$i]->scenario = $scenario;
}
return $models;
}
private function validateModels($forms, $models) {
$valid = true;
foreach($forms as $k => $form) {
$models[$k]->attributes = $form;
$models[$k]->position = $k;
$valid = $models[$k]->validate() && $valid;
}
return $valid;
}
private function saveModels($models, $company_id) {
foreach($models as $k => $model) {
$model->company_id = $company_id;
if($model instanceOf File) {
if($model->save()) $this->upload_file($model, "file");
} else $model->save();
}
}
private function upload_file($model, $field, $k) {
$path = Yii::app()->basePath . "/../assets/files/companies/{$model->company_id}/";
$file = CUploadedFile::getInstance($model, $field);
if($file instanceof CUploadedFile) $model->$field = $file;
if($model->$field instanceof CUploadedFile) {
if(!file_exists($path)) exec("mkdir -p {$path}");
$model->$field->saveAs($path . $model->$field);
}
}
I've tried everything but I can't fix it, any suggestion?
Thanks.
I am not sure if this assignment $models[$k]->attributes = $form; will do the $_FILES as well as the $_POST for your model. Looking at this example, I think you need to do that CUploadedFile stuff before you validate() or save() (which also validates), otherwise your file field will be blank.
I think you need this order of events:
$model->$field = CUploadedFile::getInstance($model, $field); // set file field
$model->save() OR $model->validate() // THEN validate
$model->$field->saveAs($path . $model->$field); // then save the file
Instead, you have this order of events currently:
$model->save() AND $model->validate()
$model->$field = CUploadedFile::getInstance($model, $field);
$model->$field->saveAs($path . $model->$field);
I could be way off though, I'm just looking at your code and not actually testing this. Also, I have no idea why it only throws an error when you set the multpart/form-data attribute on the form; it should not work at all without that! Maybe it was skipping validation on the file fields without that? Or attributes() was assigning something from $_POST besides the file? /shrug
UPDATE:
Another thing that might be happening, is that with "tabular" input you need to reference the input field with the '$key' as well (i.e. Model[0][imageFile]). So here, where you are calling:
$this->upload_file($model, "file");`
You probably need to call something like this, so that getInstanceByName() is getting the right field name:
$this->upload_file($model, "[".$k."]file");`
I think you will still need to re-arrange your code as I mention above too.
Good luck!
More reading:
Yii forum post about this subject
Your same question in the Yii forum
I did register form in with zend form
$password = new Zend_Form_Element_Password('password');
$password->setLabel($this->_translate->_("Password:"))
->setRequired(true)
->addValidator('stringLength', true, array(4, 32));
$confirmPassword = new Zend_Form_Element_Password('confirmpassword');
$confirmPassword->setLabel($this->_translate->_("Confirm Password:"))
->setRequired(true);
I control password and confirmpassword in controller. if password and confirmpassword don't match then add error message under confirmpassword textbox. how i do?
Override isValid in your form
/**
* Validate the form, check passwords.
*
* #param array $data
* #return boolean
*/
public function isValid($data) {
$valid = parent::isValid($data);
if ($this->getValue('password') !== $this->getValue('password2')) {
$valid = false;
$this->password2->addError('Passwords don\'t match.');
}
return $valid;
}
The concept basically boils down to adding a Zend_Validate_Identical validator to the 'confirmpassword' field, using the data from the $this->_request->getParam('password') to test against. I use a custom method on an extended Zend_Form to process the post data from all my forms, it isn't an exact solution for you, but perhaps my code from my "EditUser" form can point you in the right direction.
From the controller:
// $form is a MW_Form_EditUser.
if ($this->_request->isPost() && $form->process($this->_request->getPost()))
{
// successful form - redirect or whatever here
}
From the MW_Form_EditUser class:
public function process(array $data)
{
// gets a copy of the user we are editing
$user = $this->getEditable();
// checks to see if the user we are editing is ourself
$isSelf = ($user->id == MW_Auth::getInstance()->getUser()->id);
// if the new_pass field is non-empty, add validators for confirmation of password
if (!empty($data['new_pass']))
{
$this->new_pass2->setAllowEmpty(false)->addValidator(
new Zend_Validate_Identical($data['new_pass'])
);
if ($curpass = $this->current_password) $curpass->setAllowEmpty(false);
}
if ($this->delete && !empty($data["delete"])) {
$this->delete->setValue(true);
$user->delete();
return true;
}
if ($this->isValid($data))
{
/// saves the data to the user
$user->email = $this->email->getValue();
$user->name = $this->name->getValue();
if ($password = $this->new_pass->getValue()) $user->password = $password;
if (!$isSelf)
{
if ($this->super->getValue()) {
$user->setGroups(array(MW_Auth_Group_Super::getInstance()));
} else {
$user->setGroups(array(MW_Auth_Group_User::getInstance()));
}
}
$user->save();
return true;
}
return false;
}
//inside form
public function isValidPSW($data) {
$valid = parent::isValid($data);
if ($data['pswd'] !== $data['pswd2']) {
$valid = false;
$this->pswd->addError('Passwords don\'t match.');
}
return $valid;
}
Using Zend_Validate_Identical is a good solution for you by Zend. I will give you another choice. jQuery. When you are using Zend_Validate_Identical form will go to the server and server will validate it. If passwords are not same it will return an error message. If you use jQuery form will not go to the server unless passwords are same.