prestashop multiple checkboxes do not save values - checkbox

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"

Related

CakePHP 2.7 GoogleChart Plugin

First of all, sorry if I'm asking for help regarding this question but I have been working on this for almost a day now. I searched this site and was able to find a post similar to my question but I cannot get it to work.
Anyway, I am using CakePHP 2.x, and I need to show reports via charts. I saw this plugin for CakePHP CakePHP GoogleCharts Plugin by Scott Harwell. I did everything step-by-step and somehow my views keep on appearing empty. I made sure it wasn't because of conflicting files so I decided to make a new CakePHP project, unfortunately, it didn't work.
Here are my codes:
Controller:
<?php
App::uses('AppController', 'Controller');
App::uses('GoogleCharts', 'GoogleCharts.Lib');
class ChartsController extends AppController {
public $uses = array('Student');
public $helpers = array('GoogleCharts.GoogleCharts');
public function test_chart(){
$student= $this->Student->getStudentAges();
$studentAgesChart= new GoogleCharts();
$studentAgesChart->type('LineChart');
$studentAgesChart->options(array('title' => "Student Ages"));
$studentAgesChart->columns(array(
//Each column key should correspond to a field in your data array
'name' => array(
'type' => 'string',
'label' => 'Student Name'
),
'age' => array(
'type' => 'number',
'label' => 'Student Age'
)
));
foreach($student as $row){
$studentAgesChart->addRow(array('age' => $row['Student']['age'], 'name' => $row['Student']['name']));
}
$this->set(compact('studentAgesChart'));
debug($studentAgesChart);
}
}
?>
View:
<div id="chart_div" >
<?php
$this->GoogleCharts->createJsChart($studentAgesChart);
?>
</div>
Debug($studentAgesChart):
object(GoogleCharts) {
[private] type => 'LineChart'
[private] columns => array(
'name' => array(
'type' => 'string',
'label' => 'Student Name'
),
'age' => array(
'type' => 'number',
'label' => 'Student Age'
)
)
[private] rows => array(
(int) 0 => array(
(int) 0 => 'Student 1',
(int) 1 => '17'
),
(int) 1 => array(
(int) 0 => 'Student 2',
(int) 1 => '16'
)
)
[private] options => array(
'width' => (int) 400,
'height' => (int) 300,
'title' => 'Student Ages',
'titleTextStyle' => array(
'color' => 'red'
)
)
[private] callbacks => array()
[private] div => 'chart_div'
}
Model:
public function getStudentAges(){
$student_ages = $this->find('all',
array(
'order' => array('Student.name' => 'ASC'),
'limit' => 3,
'fields' => array(
'Student.name',
'Student.age'
)
)
);
return $student_ages;
}
The way I see it, it doesn't contain any errors but my view is empty.
#Scrappy, do you see any output (JavaScript or HTML) included in the DOM when you view source on your page? Or, is the plugin not generating any content at all? If you do see JavaScript code added, is your page reporting JS errors in the console that might prevent the chart from loading properly? If you do not see the JS code, then you likely have not loaded the plugin in your bootstrap file.
Is the page available on the public Internet for review?
The plugin has not seen updates from me in a few years, but there are a few developers that have forked it and updated it for CakePHP 3.0 too. But, this version should still be working unless something changed on the Google end, which I am sure I would have heard about if that was the case.

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

Adding a default option "Please Select" in cakephp dropdown

I am new to cakephp. I need to add a default
<option value="0">--Please Select--</option>
in my following select field :
$attributes = array("empty"=>false,"Selected" => 'Select City',"id" => "location");
echo $form->select("gal_location_id", $gal_locations,null,$attributes);
I tried to add
$gal_locations[0] = "--Select City--";
$attributes = array("empty"=>false,"default" => 0,"id" => "location");
but the option coming at the bottom of the list. What is the proper way to add the default option ?
You're looking for the "empty" attribute:
$this->Form->input('gal_location_id', array(
'type' => 'select',
'options' => $gal_locations,
'empty' => 'Select City', // <-- Shows as the first item and has no value
'id' => 'location'
));
See the equivalent in CakePHP3 from this post
CakePHP3
With the following option you dont get a notification to choose a dropdown item.
So if you're just looking for a default value and force the user to pick another, just replace the assign a string to 'empty'.
echo $this->Form->input('db_field', [
'label' => 'My Drop Down',
'empty' => [$default => $default], //Your default options
'options' => $my_options //Your array /list'
]);
echo $this->Form->input('country_id',[
`enter code here`'options' =>$country,
'label' => false,
'class'=>'form-control select2',
'empty'=> 'Select...',
'value' => ''
]);

cakephp How can I convert passed params to named params to prefill element form?

I'm using CakePHP version 2.2.3 I have an element with a search box and a few dropdowns that use CakeDC's search plugin. It works great and just passes the selected/searched items in the URL like this www.mydomain.com/products/cid:1/mid:3/terms:these%20terms where cid is category id, and mid is manufacturer id.
I created pages that allow you to click a category to find all products in that category, but I can't get the category select box, in the element, to select the category of the page it is on. It works if I use the same URL structure as my element submits but I want a clean URL for SEO so I setup the following custom route:
/**
* Categories
*/
Router::connect(
'/products/category/:cid-:slug', // E.g. /products/category/3-my_category
array('controller' => 'products', 'action' => 'category'),
array(
'pass' => array('cid', 'slug'),
'cid' => '[0-9]+'
)
);
this results in a nice looking URL but doesn't pre-select the value of my select list.
I was able to get it working with the code below in my element, but it seems "hacky/clunky"
if(isset($this->params['named']['cid']) && !empty($this->params['named']['cid'])){
echo $this->Form->input('cid', array('label' => false, 'default' => $this->params['named']['cid'], 'options' => $categories, 'empty' => ' ( Category ) '));
}elseif(isset($this->params['pass']['0']) && !empty($this->params['pass']['0'])){
echo $this->Form->input('cid', array('label' => false, 'default' => $this->params['pass']['0'], 'options' => $categories, 'empty' => ' ( Category ) '));
}else{
echo $this->Form->input('cid', array('label' => false, 'options' => $categories, 'empty' => ' ( Category ) '));
}
Also, in my controller I've tried this:
$this->params['named']['cid'] = $this->params['pass']['0'];
but I get this error: Indirect modification of overloaded element of CakeRequest has no effect
I believe the plugin automatically sets the selected value if using named params, unless thats a default behavior of cake. How can I convert the passed params to named params, or can I force my plugin to use passed params?
output from var_dump($this->$params):
object(CakeRequest)[9]
public 'params' =>
array
'plugin' => null
'controller' => string 'products' (length=8)
'action' => string 'category' (length=8)
'named' =>
array
empty
'pass' =>
array
0 => string '2' (length=1)
1 => string 'This_and_that' (length=13)
'cid' => string '2' (length=1)
'slug' => string 'This_and_that' (length=13)
public 'data' =>
array
empty
public 'query' =>
array
empty
Thanks

Drupal allowed_values_function does not get called when creating a field

For some reason my allowed_values_function never gets called when showing a field on a user bundle. Code:
function get_business_units()
{
$options = entity_load('business_unit', FALSE, NULL, FALSE);
$opt = bu_to_list_values($options);
return $opt;
}
function MYMODULE_enable()
{
if (!field_info_field('field_user_business_unit')) {
$field = array(
'field_name' => 'field_user_business_unit',
'type' => 'text',
'settings' => array(
'allowed_values' => array(),
'allowed_values_function' => 'get_business_units',
)
);
field_create_field($field);
// Create the instance on the bundle.
$instance = array(
'field_name' => 'field_user_business_unit',
'entity_type' => 'user',
'label' => 'Business Unit',
'bundle' => 'user',
'required' => FALSE,
'settings' => array(
'user_register_form' => 1,
),
'widget' => array(
'type' => 'options_select',
),
);
field_create_instance($instance);
}
}
The field is created, and even displayed on the users "edit" page when editing their info. But the only value is "Select" or "None". My method is never called (I even placed a debug point). This is all in MYMODULE.install file.
The problem is: 'type' => 'text'.
You have to use: 'type' => 'list_text'.
Allowed values is meaningless for a text type.
Your get_business_units() function needs to be in the MYMODULE.module file; the .install files aren't included in a normal Drupal bootstrap.
Have you tried
drush features-revert MYMODULE ?

Resources