I'm building a simple message system using Zend Form where users will be able to select multiple recipients. Each recipient may be a different user type and so I need to have both the user type and the ID to send to the servicelayer. The form will start off with one recipient selected (as an array element in the form), and I plan to use jQuery to append each subsequent recipient to said array. I wish to end up with this:
array(4) {
["Subject"] => string(4) "My message subject"
["Body"] => string(6) "My body of text"
["Recipients"] => array(1) {
[0]
["profile"] => string(2) "476"
}
[1]
["otherusertype"] => string(1) "54"
}
}
}
This would enable me to loop through each recipient nice and easily, gaining the user type and the respective ID.
Now, I am currently doing this in Zend Form:
$form->addElement(
'hidden',
$type,
array(
'value' => $id,
'belongsTo' => 'Recipients'
)
);
But this leaves me with
array(4) {
["Subject"] => string(4) "hfgh"
["Body"] => string(6) "fghfgh"
["Recipients"] => array(1) {
["profile"] => string(1) "1"
}
}
As you can see, if I add another recipient of usertype "profile" to the array, it will just be overwritten.
How am I able to get an extra dimension within this array?
Thanks in advance!
You should set your belongsTo to the array:
$this->addElement('hidden', '1', array(
'value' => 1,
'belongsTo' => 'Recipients[profile]'
));
$this->addElement('hidden', '2', array(
'value' => 2,
'belongsTo' => 'Recipients[profile]'
));
Related
I have a trouble validating an array members in validation for Laravel. For array itself it passes, but for elements themselves, it fails.
Open json in console, shows structure of data being sent. It's clearly a integer. Since it's associative array, not sure how it even finds it's value as show in error handling red rectangle on the bottom of the page.
Here is my validation logic:
$validation = Validator::make(
$request->all(),
[
'load_place' => 'required|max:255',
"unload_place" => 'required|max:255',
"comment" => 'required|max:255',
'time_in' => 'required',
'time_out' => 'required',
"vehicles" => 'required|array',
"vehicles.*" => "required|integer",
'operator_id' => 'required|integer',
'sec_id' => 'required|integer'
]
);
And here is how it's returned:
if($validation->fails()){
$response = array(
"message" => "Failed",
"errors" => $errors,
"test" => $request->vehicles[0]
);
return response()->json($response);
}
That request[0], is that number at the bottom.
Edit1:
Keys in that marked array, are set on frontend, they are not not predefined. They can be whatever.
Change "vehicles.*" => "required|integer", to "vehicles.*.vehicle_id" => "required|integer", and it should work.
Keys is set on frontend, they are not not predefined. That what i am trying to say.
Try to replace "vehicles.*" => "required|integer", with new Rule::forEach rule for nested array data - guess it should work.
"vehicles.*" => Rule::forEach(function($value, $attribute) {
return [
Rule::integer()->min(1) //min(1) as eg if it's for an id field which cannot be 0
];
}),
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"
I have a form for creating a task, and when creating it, user is asked to select which employees will be assigned to it. There may be just one employee or even up to 10. I allow user to dynamically create those input fields on the go, but the array that i get after the form submition looks like this:
array(
'Event' => array(
'project_id' => '62',
'user_id' => '23',
'user_id2' => '24',
'user_id4' => '28',
'user_id8' => '30',
'hours' => '6',
'minutes' => '0',
'assignment' => '',
'material' => 'safsaf',
'date' => '2013-10-12',
)
)
The problem is I do not know how to iterate over the user_ids.
Is it possible to save the IDs as a list? Or is there any other solution?
Use CakePHP's find('list') to retrieve the $users in an key=>value array, then set the multiple attribute of the input to true:
echo $this->Form->select('Model.field', $users, array('multiple' => true));
$attributes['multiple'] If ‘multiple’ has been set to true for an
input that outputs a select, the select will allow multiple
selections:
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.
I am creating a Wordpress theme that catalogs albums, and I have created the custom post type, created the custom fields, and have them successfully pulling in. I have several custom fields including; Artist, Album, Size, Label etc. I currently have the posts sorting alphabetically by the Artist name with this array:
$args=array(
'post_type' => 'albums',
'order' => 'ASC',
'meta_key' => 'custom_meta_artist',
'orderby' => 'meta_value',
'posts_per_page' => -1,
);
But I would also like the Albums, 'custom_meta_album', to sort alphabetically if it is the same Artist. Currently if a user enters in 10 albums by the same artist, the post will be alphabetized correctly by the Artist name, but the Albums have no order.
Is there a way to do some sort of second level sorting or primary and secondary sorting in Wordpress? I don't know if it's a IF statement that says "if artists value is equal then also sort albums ascending" or something along those lines. I figure there needs to be some way to tell Wordpress which field it should sort by first and then continue to the second level.
You may try this, hope this will work
// keep this function in your functions.php
function myCustomOrderby($orderby) {
return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
}
This is your args array
$args=array(
'post_type' => 'albums',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'custom_meta_artist',
'value' => '',
'compare' => 'LIKE'
),
array(
'key' => 'custom_meta_album',
'value' => '',
'compare' => 'LIKE'
)
)
);
add_filter('posts_orderby','myCustomOrderby'); // Add filter before you call the WP_Query
$albums = new WP_Query($args);
remove_filter('posts_orderby','myCustomOrderby'); // Remove filter after you call the WP_Query
// Start your loop
while ( $albums->have_posts() ) : $albums->the_post();
//...
endwhile;