CodeIgniter Callback Problem - php

I have an application that allows users to create forms and assign validation to each field (think http://www.phpform.org/ or http://wufoo.com/). I can easily get each field’s name and label from the database, as well as the array of associated validation rules.
Say, for example, I wanted to apply a blanket rule of “required” for all of the user defined forms, I would do something like this:
foreach($fields as $field)
{
$this->form_validation->set_rules($field[‘name’], $field[‘label’], ‘required’);
}
Now, the problem is that I need to replace “required” with a callback. In order for the callback to work, I’m going to need the field’s id (so the callback can use this id to lookup the field's associated validation rules). How do I get this id value to the callback function?

foreach($fields as $field)
{
$this->form_validation->set_rules($field[‘name’], $field[‘label’], "callback__example[$field[‘id‘]]");
}
// your callback... see ~line 589 of Form_validation library
public function _example($str,$id)
{
// do something to $str using $id, return bool
}

Related

How to make a redirect with an array of data in codeigniter 4?

Codeigniter 4 has the ->with($key, $value) method for redirect which sets 1 value in flashdata.
However, I need to pass an array of data to with. Codeigniter supports setting flashdata using the array (session()->setFlashdata($someArray)), but this is not provided for with (well, or I searched badly).
Now I have achieved the desired result as follows. Controller method example:
public function makeAction()
{
$result = $this->someModel->makeSomeAction();
if(empty($result['errors']))
{
// Some
}
else
{
$errors = $result['errors'];
$redirect = redirect()->to('/some/link');
foreach($errors as $key=>$value)
$redirect->with($key, $value);
return $redirect;
}
}
However, I would like to be able to either pass an array in with, or make a withArray method into which to pass an array. How can this be achieved, preferably without touching the system files? Can make any Event event?
P.S. In a slightly newer version, I found the withErrors() method, which is not in the documentation, but it is specifically intended for validation errors, and not for any other errors.

Yii framework validation rules

I am using Yii 1 for my project. I have 5 fields in a form, which must be filled. There's no problem with that - a simple validation rule in model. However, there is one more field, which is not required. But if it is filled, other 5 fields must become not-required. How should I define such validation rules in rules() method in model?
Thank you in advance very much!
Try playing with scenarios. When you validate your data, check if this field is filled and create new model with specific scenario.
Look here
you can create your own custom validation rule so you can skip scenarios, you will need to:
Stating that:
$model->TRIGGERATTR = is the attribute that if informed is going to indicate that the other 5 are required
$model->ATTR1 = one of the five other attributes
$model->ATTR2 = two of the five other attributes
.
.
. and so on...
Declare your rule inside your model like :
array('ATTR1, ATTR2, ATTR3, ATTR4, ATTR5','{NameofRule}Validator'),
Create a custom validation inside your components/validators/general/{NameofRule}Validator
with the following code
class {NameofRule}Validator extends CValidator
{
public function validateAttribute($model, $attribute)
{
if((isset($model->TRIGGERATTR))&&(!is_null($model->TRIGGERATTR))
{
if(!isset$model->$attribute||is_null($model->$attribute))
{
$this->addError($model, $attribute, 'Is not Informed and it should be');
}
}
}
}
Don´t forget to add your comments and mark as solved ;-)

Large form validation structure

I'm currently building a form manager in PHP to validate large forms.
I'm wondering what is the best structure for that, because the number of fields will be different each time.
I'm already filtering the field to validate by using a prefix (ex : 'user_name', will be validated, but 'name' no).
My real problem is for the validation : I must check the type of the field (mail, zipcode, phone...)
AND check that the value for this type of field is valid.
I thought that I could use HTML5 Custom data" (ex: data-fieldtype="zipcode"), but i didn't know that the server can't get this attribute...
What's the way to go ?
I could use 2 inputs per field, one for the value and one for the type, but it looks really stupid !
Thanks if you can help.
EDIT :
Your answers are all interesting, i don't know which is best.
I will probably make a mix between your solutions, depending of the kind of form.
Thanks a lot.
Methinks, this shouldn't be played via the Browser without further thought: A malicious user would be able to manipulate a "INT ONLY" field into being freetext, and your application would suddenly have to deal with freetext in a field, that is thought to be validated as an integer (und thus e.g. safe for SQL).
You have two approaches:
Have your form validation structure stored in the DB, and submit a single hidden field, that carries the ID of the validation structure. On receiving the request, your script would request the structure from the DB, unserialize it, and work on it.
If you really need to go through the browser, serialize your validation structure, base64-encode it and use it as a single hidden field. For the reasons stated above, it is mandatory to authenticate this value, either hashing (concatenate with another string only known to the server, hash it, send the hash as a second hidden field, on next request verify the hash is correct) or by encryption (encrypt the serialized data before the browser roundtrip, decrypt afterwards, key known only to the server)
Both would make your prefix-trick unnecessary, increasing readability and maintainability.
If no framework is used, you can use an array of field => options.
$rules = [
'user_name' => 'required',
'user_email' => 'email required',
// ...
];
And then feed them to some validator class, where rules are methods and they're being called inside validate method dynamically:
class Validator {
public function __construct($data) { $this->data = $data; }
private function required($field) {}
private function email($email) {}
// etc
/** #method bool validate(array $rules) */
public function validate($rules) {}
}
Never ever validate on client-side only. Always validate serverside.
Usually you will have a base class for controller, and every other controller extends it.
Aa good approach is to have en every view controller (or the bootsrtap) a method check_params().
It should 1) get a copy or $_REQUEST, check every parameter needed, 2) delete $_REQUEST, 3) write back the checked and validated params.
abstract class controller_base {
public function __construct() { ...; $this->check_param();...}
protected final function check_param() {
foreach ($this->param_list() AS $name => $type) {...}
}
abstract public function param_list();
}
class controller_login extends controller_base {
public function param_list() {
return array('name' => 'string', 'password' => 'string');
}
}
The idea is that this way you
only use params that has been sanitized
you autmaticly delete every param not needed
you have a list in every controller that states the used params.

Yii framework: passing variable through Chtml:button

I am trying to pass a variable from a view (of mobile model) to a different controller (of inventory model), using the chtml:button with this code
echo CHtml::button(
'Sell It',
array('submit' => array('inventory/create', array('id'=>$data->id)))
);
Now how do I access the $id variable in the Inventory controller, so that I can prepopulate the create view with details corresponding to the passed 'id' variable of the mobile model.
In your inventory/create controller action do checking before getting the id like this :-
if (isset($_REQUEST['id'])) {
$id = $_REQUEST['id'];
$this->render('create',array('model'=>$inventory, 'id'=>$id));
}
else{
$this->render('create',array('model'=>$inventory);
}
If you are trying to come up an update/edit form with the values prefilled based on the Id passed then you should have to go through the CRUD options available within YII.. This is much better way to handle record updation and its easy too . See this topic for furhter info..
http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
In your inventory/create controller action do a test for $_GET['id'] something like:
$id = (#$_GET['id']) ? : DEFAULT_VALUE;
$this->render('create',array('model'=>$inventory, 'id'=>$id));
and then you pass the data through to the view by passing an array of variables you want to make available.
(you would want to filter the input better, this is just a sample -- using filter_input or some other method and define a default value and/or some test for it being null/invalid)
in your controller you can get the variable by giving an argument to your controller method like this:
public function actionCreate($id){
$id = isset($id)?$id:NULL; // Or whatever, you can access it like this.
}
You don't have to use $_GET, and yii has already done some security checks on the value.

need some help figuring out how to approach this validation

I am using codeigniter for my form validation. I have two select fields named parent_male and parent_female. I would like to have a validation callback to check both the parent_male and parent_female in my database to see if it exists. I already have a previous callback function that does just that, but with only one field. I would like to check the two field values against the database, except I am not sure how to approach this idea. Any help/ideas are greatly appreciate! Thank you.
-Rich
You can define your callback as:
function isparent($parent) {
$result = FALSE;
/* do your stuff to check $parent is a valid parent and then ... */
return $result;
}
and the rules can be set as
$this->form_validation->set_rules('parent_male', 'Male parent', 'callback_isparent');
$this->form_validation->set_rules('parent_female', 'Female parent', 'callback_isparent');
In that way you use the same callback for both fields.

Categories