CakePHP 2.2 validation trim() error - cakephp

This is quite strange, I have a text input in a registration form and when I am setting the $validate array in the model, I am getting a trim() error - Warning (2): trim() expects parameter 1 to be string, array given [CORE\Cake\View\Helper.php, line 754]
Form input
<?=$this->Form->input("lastname", array("label" => array("text" => "Last name *"), "class" => "required", "div" => array("class" => array("input text last")))); ?>
Model validate array
public $validate = array(
'lastname' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Last name is required'
)
)
);
It seems that when I am doing a validation rule for that field, the div styling array - "div" => array("class" => array("input text last")) is causing the error. I added the following code to the Helper.php file as a workaround:
if(is_array($options["class"])) {
$options["class"] = $options["class"][0];
}
but I would like to know why it is causing this error.

Too many nested arrays for the Form Helper. Try this:
$this->Form->input("lastname", array(
"label" => "Last name",
"id" => "MyInputDiv",
"class" => "input text last required"));
array("text" => "Last name *") You don't need an array here if you are just setting the text value of the label. Array is reserved for html attributes.
"div" => array("class" => array("input text last")) Not familiar with this in the formHelper. Perhaps you were looking for the before and after attributes to set the wrapping div of the element here.

Related

prestashop multiple checkboxes do not save values

I can't figure out why the checkbox values are not saved in the database using helpers.
Trying to save some customers ids from my module's setting :
The array :
$custs = Customer::getCustomers();
foreach ($custs as $key => $value) {
$options[] = array(
'id_customer' => (int)$value['id_customer'],
'infos' => $value['firstname'].' '.$value['lastname'].' | '.$value['email']
);
}
The checkboxes :
'input' => array(
array(
'type' => 'checkbox',
'label' => $this->l('Customers'),
'desc' => $this->l('Select the Customers.'),
'name' => 'MY_MODULE_CUSTOMERS',
'values' => array(
'query' => $options,
'id' => 'id_customer',
'name' => 'infos',
),
),
)
The $_POST is always empty but works well with another input. Any help will be appreciated.
Thank you.
I don't think its in PS docs. But with a bit of code inspecting you can see in
Backoffice/themes/default/template/helpers/form/form.tpl
<input type="checkbox" name="{$id_checkbox}" id="{$id_checkbox}" class="{if isset($input.class)}{$input.class}{/if}"{if isset($value.val)} value="{$value.val|escape:'html':'UTF-8'}"{/if}{if isset($fields_value[$id_checkbox]) && $fields_value[$id_checkbox]} checked="checked"{/if} />
{$value[$input.values.name]}
add the porperty 'val' to option.
$options[] = array(
'id_carrier' => $carrier['id_carrier'],
'name' => $carrier['name'],
'val' => $carrier['id_carrier'],
);
Adn you get the desired serialization for the input values.
"transportistas" => array:2 [▼
0 => "73"
1 => "78"
]
Your code is correct, I tried it and this is result
http://screencast.com/t/wfsW86iJj
You have to click at least one checkbox.
Show data on server :
print_r($_POST);
die();
a better could be using groupbox but its quite difficult, take a look to the AdminCustomers controller class in the controllers directory of the prestachop, this has a multiselect group that used a relational table event stored in single field
If you want to be easy, using a single field to store in the database, take a look to THE COMPLETE CODE AND ALL THE STEPS AT: https://groups.google.com/forum/m/?hl=es#!topic/venenuxsarisari/z8vfPsvFFjk
at the begining dont forget to added that line:
// aqui el truco de guardar el multiselect como una secuencia separada por comas, mejor es serializada pero bueh
$this->fields_value['MY_MODULE_CUSTOMERS[]'] = explode(',',$obj->id_employee);
this $obj are the representation of the loaded previous stored value when go to edit ... from that object, get the stored value of the field of your multiselect, stored as "1,3,4,6"
and the in the field form helper list of inputs define the select multiple as:
array(
'type' => 'checkbox',
'label' => $this->l('Select and employee'),
'name' => 'MY_MODULE_CUSTOMERS[]',
'required' => false,
'col' => '6',
'default_value' => (int)Tools::getValue('id_employee_tech'),
'values' => array(
'query' => $options,
'id' => 'id_customer',
'name' => 'infos',
),
),
an then override the post process too
public function postProcess()
{
if (Tools::isSubmit('submitTallerOrden'))
{
$_POST['MY_MODULE_CUSTOMERS'] = implode(',', Tools::getValue('MY_MODULE_CUSTOMERS'));
}
parent::postProcess();
}
this make stored in the db as "1,2,3"

drupal form field not loading correct data

I am building my first Drupal 7 module and am having trouble with the screen to edit a fieldable entity. I am using field_attach_form and it is working great for all accept one field which is displaying the field default rather than the current content of that field for that entity.
I have a text field, a number field, a number of Boolean fields and the one list_text field which is failing.
Any ideas what I a doing incorrectly? Code below is what I think is needed but please do let me know if you need more.
Code to create the field in hook_enable:
if (!field_info_field('field_available')) {
$field = array (
'field_name' => 'field_available',
'type' => 'list_text',
'settings' => array(
'allowed_values' => array('No', 'Provisionally', 'Yes'),
),
);
field_create_field($field);
Code to create the instance, also in hook_enable:
if (!field_info_instance('appointments_status', 'field_available', 'appointments_status')) {
$instance = array(
'field_name' => 'field_available',
'entity_type' => 'appointments_status',
'bundle' => 'appointments_status',
'label' => t('Available?'),
'required' => TRUE,
'default_value' => array(array('value' => 'No')),
'description' => t('Set to No if appointments with this status make this slot unavailable, Provisionally means that it will only reserve a space temporarily'),
);
field_create_instance($instance);
This entity has only the one bundle with the same name as the entity.
The code to create the URL in hook_menu:
$items['admin/appointments/appointments_statii/%/edit'] = array(
'title' => 'Edit appointment status',
'description' => 'Edit the parameters of the selected status code',
'page callback' => 'drupal_get_form',
'page arguments' => array('appointments_status_edit_form',3),
'access arguments' => array('access administration pages'),
'type' => MENU_CALLBACK,
);
The form function is:
function appointments_status_edit_form($form, &$form_state) {
// Get the status id from the form_state args
$status_id = $form_state['build_info']['args'][0];
// Load the chosen status entity
$status = entity_load_single('appointments_status', $status_id);
// Set up the fields for the form
field_attach_form('appointments_status', $status, $form, $form_state);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Save changes',
'#weight' => 99,
);
return $form;
}
I have used the Devel module's dpm to check that the data is loaded correctly by entity_load_single and it is.
Thanks
Rory
I have answered my own question!
I was also programmatically loading some entities and was not loading this field with the numbers that a list_text field stores, instead I was loading the visual text.
I used a metadata wrapper and the code looked like this:
$w_appointments_status->$appointments_availability= 'Yes';
I changed it to:
$w_appointments_status->$appointments_availability = 2;
In this example 'Yes' was the third allowed value - hence 2.
So the code in my question was in fact correct although I have since added 'widget' and 'formatter' parameters to the instance.
I am sorry if this got some of you scratching your heads thinking ' but that code is correct'!!
Regards
Rory

CakePHP inputDefaults and rewrite by field

I've created a large form in Cake and set default options via inputDefaults. However I wish to change the default values for an individual field.
In setting the form defaults, I wrote approximately this:
'inputDefaults' => array(
'error' => array(
'attributes' => array(
'wrap' => 'span',
'class' => 'invalidate column-7 offset-3')));
...with the result that all like fields produce the same error message. But, when I attempt to change the defaults for a single field, like so:
echo $this->Form->input('name', array(
'error' => array(
'attributes' => array(
'wrap' => 'span',
'class' => 'invalidate column-10'))));
It doesn't work. The field name produces an error whose class reads column-7 and offset-3, whereas I'd intended column-10.
Anybody know a solution?
$options['inputDefaults'] You can declare a set of default options for input() with the inputDefaults key to customize your default input creation:
echo $this->Form->create('User', array(
'inputDefaults' => array(
'label' => false,
'div' => false
)
));
All inputs created from that point forward would inherit the options declared in inputDefaults. You can override the defaultOptions by declaring the option in the input() call:
echo $this->Form->input('password'); // No div, no label
// has a label element
echo $this->Form->input(
'username',
array('label' => 'Username')
);

CakePHP Validation depending on other field

I wonder if it is possible with CakePHP validation rules to validate a field depending on another.
I have been reading the documentation about custom validation rules but the $check param only contains the value of the current field to validate.
For example. I would like to define the verify_password field as required only if the new_password field is not empty. (in case
I could do it with Javascript anyway but i wonder if it is possible to do it directly with CakePHP.
When you validate data on a model, the data is already set(). This means that you can access it on the model's $data property. The example below checks the field we're validating to make sure it's the same as some other field defined in the validation rules (such as a password confirm field).
The validation rule would look something like this:
var $validate = array(
'password' => array(
'minLength' => array(
'rule' => array('minLength', 6),
'message' => 'Your password must be at least 6 characters long.'
),
'notempty' => array(
'rule' => 'notEmpty',
'message' => 'Please fill in the required field.'
)
),
'confirm_password' => array(
'identical' => array(
'rule' => array('identicalFieldValues', 'password'),
'message' => 'Password confirmation does not match password.'
)
)
);
Our validation function then looks at the passed field's data (confirm_password) and compares it against he one we defined in the rule (passed to $compareFiled).
function identicalFieldValues(&$data, $compareField) {
// $data array is passed using the form field name as the key
// so let's just get the field name to compare
$value = array_values($data);
$comparewithvalue = $value[0];
return ($this->data[$this->name][$compareField] == $comparewithvalue);
}
This is a simple example, but you could do anything you want with $this->data.
The example in your post might look something like this:
function requireNotEmpty(&$data, $shouldNotBeEmpty) {
return !empty($this->data[$this->name][$shouldNotBeEmpty]);
}
And the rule:
var $validate = array(
'verify_password' => array(
'rule' => array('requireNotEmpty', 'password')
)
);

cakePHP "required" validation

is there any mistake in this validation???
var $validate = array(
'brand_id' => array(
'required' => array(true),
'message' => array('select a brand'),
)
);
brand_id is a select box
It show error as "message" instead of "select a brand"
if the message is not in array it shows error
Warning (2): preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash [CORE\cake\libs\model\model.php, line 2571]
using cakePHP 1.3
You're missing a rule, just required won't do. Use 'notEmpty' as rule if that's what you want. Also, required and message should (must?) not be arrays.
Why do you have arrays everywhere?
var $validate = array(
'brand_id' => array(
'required' => true,
'message' => 'select a brand',
)
);
Refer to:
http://book.cakephp.org/1.3/en/The-Manual/Common-Tasks-With-CakePHP/Data-Validation.html

Resources