Hello i'm using Google Charts Plugin to my CakePHP application.
In my Controller i do:
There are two functions that return two graphs.
function statistics() {
$this->timePerClient();
$this->timePerProjectChart();
}
FUNCTION timePerProject
function timePerProjectChart() {
$totalProjeto = $this->timePerProject();
$tempoTotalGasto = $this->tempoTotalInvestido();
//Setup data for chart
$timePerProjectChart = new GoogleChart();
$timePerProjectChart->type("PieChart");
$timePerProjectChart->options(array('title' => "Percentagem de Tempo (horas) investido por Projeto"));
$timePerProjectChart->columns(array(
//Each column key should correspond to a field in your data array
'projects' => array(
'type' => 'string',
'label' => 'Projeto'
),
'tempoGasto' => array(
'type' => 'time',
'label' => '% horas'
)
));
//You can also use this way to loop through data and creates data rows:
foreach ($totalProjeto as $row) {
$percentagemTempoGasto = ($this->timeToHour($row[0]['tempogasto']) / $tempoTotalGasto[0][0]['tempogasto']) * 100;
$timePerProjectChart->addRow(array('tempoGasto' => $percentagemTempoGasto, 'projects' => $row['Project']['pname']));
}
//Set the chart for your view
$this->set('timePerProjectChart', $timePerProjectChart);
}
In my view (statistics) i do :
<div id="chart_div" ><?php $this->GoogleChart->createJsChart($timePerProjectChart);
$this->GoogleChart->createJsChart($timePerClientChart);
?></div>
but I just can not see a single graph. I tested (individually) each and are functioning.
I'll wish to put multiple charts on the same view.
Is it possible?
thanks
What is happening in your statistics action in your controller? $this is an object.
There are a couple steps required to use the plugin: '
Get data. Use a find or other model method to get the data you want.
Set up the chart:
$chart->type("LineChart");
$chart->options(array('title' => "Recent Scores"));
$chart->columns(array(
//Each column key should correspond to a field in your data array
'event_date' => array(
//Tells the chart what type of data this is
'type' => 'string',
//The chart label for this column
'label' => 'Date'
),
'score' => array(
'type' => 'number',
'label' => 'Score'
)
));
Add rows to your chart by looping through data, an example is given below
foreach($model as $round){
$chart->addRow($round['Round']);
}
Set the chart for your view- this is the same name that must be then called in <div id="chart_div"><?php $this->GoogleChart->createJsChart($chart);?></div> in the view.
$this->set(compact('chart'));
To display more than one chart in a single view, you need to not just use the default chart_div as the id of your div. You need to set two different divs and update the objects accordingly:
set
<?php $timePerProjectChart->div('projectChart');?>
<?php $timePerClientChart->div('clientChart');?>
<div id="projectChart"><?php $this->GoogleChart->createJsChart($timePerProjectChart);?></div>
<div id="clientChart"><?php $this->GoogleChart->createJsChart($timePerClientChart);?></div>
Related
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 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
Cane Somebody give me an ideas on this Please!
I Generate multiple checkboxes from a table that is related with another table with HABTM relationship association.
I would like to generate multiple checkboxes with an image along with the text in the label.
My two tables are items and items_characteristics. So an Item HasAndBelongToMany characteristics, and an ItemCharacteristic HasAndBelongToMany Items.
echo $this->Form->input('Item.ItemCharacteristic',array(
'label' =>false,
'type'=>'select',
'multiple'=>'checkbox',
'options' => $itemCharacteristics ,
'selected' => $this->Html->value('ItemCharacteristic.ItemCharacteristic')
));
This code generate the list of the checkboxes properly and works perfect:
This is what i have:
Which is generated from DB from the table items_characteristics.
And this is what i wanna have:
Does Anyone have any Idea how i can achieve this Please?
I assume that in your controller you did something like:
$this->request->data = $this->Item->find('first', ... );
so that $data contains the information about selected characteristics in form of a subarray,
edit: I also assume that Item habtm ItemCharacteristic
then in your view
$checked_characteristics = Hash::extract($this->data, 'ItemCharacteristic.{n}.id');
foreach($itemCharacteristics as $id => $itemCharacteristic )
{
$checked = in_array($id, $checked_characteristics );
$img = $this->Html->image('cake.icon.png'); // put here the name
// of the icon you want to show
// based on the charateristic
// you are displayng
echo $this->Form->input(
'ItemCharacteristic.ItemCharacteristic.',
array(
'between' => $img,
'label' => $itemCharacteristic,
'value' => $id,
'type' => 'checkbox',
'checked' => $checked
)
);
}
edit: from your comment I understand that $itemCharacteristics come from a find('list') statement.
change it into a find('all', array('recursive' => -1));
now your code becomes
foreach($itemCharacteristics as $itemCharacteristic )
{
$id = $itemCharacteristic['ItemCharacteristic']['id'];
$icon_name = $itemCharacteristic['ItemCharacteristic']['icon_name']; //or wherever you get your icon path
$img = $this->Html->image($icon_name);
$itemCharacteristicName = $itemCharacteristic['ItemCharacteristic']['name'];
// same as above
}
I have the following code setup (snipped for brevity)
class BasePackage extends AppModel {
public $name = 'BasePackage';
public $hasAndBelongsToMany = array('ProductSubtype', 'ProductType');
}
class ProductType extends AppModel {
public $name = 'ProductType';
}
class ProductSubtype extends AppModel {
public $name = 'ProductSubtype';
}
Above are the simple Model classes.
/* tables in database */
base_packages
product_types
product_subtypes
base_packages_product_types
base_packages_product_subtypes
The first table is the main package that users are creating with the form, the product_* tables are pre-loaded with appropriate types and subtypes (they don't change very often), the last two are the Join tables that CakePhp wants to have
/* in BasePackage/add.ctp */
// ...
<ul class="nwblock">
<li>
<?php
echo $this->Form->input('ProductType.product_type_id', array(
'label' => 'Choose Product Type',
'type' => 'select',
'class' => 'form-control',
'style' => 'width:300px; margin-bottom:20px;',
'options' => $protypes
));
?>
</li>
</ul>
<ul class="nwblock">
<li>
<?php
echo $this->Form->input('ProductSubtype.product_subtype_id', array(
'label' => 'Choose Subtype(s)',
'multiple' => 'multiple',
'type' => 'select',
'class' => 'form-control',
'style' => 'width:300px;height:390px;margin-bottom:20px;',
'options' => $subtypes
));
?>
</li>
</ul>
// ...
Above we see the two controls that are loaded from the product_* tables. The types are a single select dropdown and the subtypes are a multiple select list.
/* in BasePackageController.php */
public function add() {
$protypes = $this->BasePackage->ProductType->find('list',
array('fields' => array('ProductType.id', 'ProductType.display')));
$subtypes = $this->BasePackage->ProductSubtype->find('list',
array('fields' => array('ProductSubtype.id', 'ProductSubtype.display')));
$this->set('protypes', $protypes);
$this->set('subtypes', $subtypes);
if ($this->request->is('post')) {
$this->BasePackage->create();
if (!empty($this->request->data)) {
$this->BasePackage->saveAll($this->request->data, array('deep' => true));
}
}
}
The process is as follows, while the user creates a new BasePackage, they select a ProductType from a dropdown box and one to many ProductSubtypes from a multiple select list. When the $this->BasePackage->saveAll() call is made, the data to be inserted into base_packages and base_packages_product_types tables is inserted correctly. However, the base_packages_product_subtypes table remains untouched.
UPDATE:
If I remove the 'multiple' => 'multiple', from the form->input options, the code saves both the producttype and the productsubtype (as expected). This is obviously not sufficient, as I need to save 1-to-many. Anyone know how to activate the 'Many' part of the HABTM?
To me BasePackage <> ProductType looks more like it should be a many-to-one relation, ie BasePackage belongsTo ProductType?
Anyways... please follow the conventions as described in the Cookbook:
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
The form helper should be fed with the model name, ie ProductSubtype, and the view var should be camel backed plural, ie productSubtypes, that way CakePHP will do the rest for you automatically.
public function add() {
// ...
$this->set('productSubtypes', $subtypes);
// ...
}
echo $this->Form->input('ProductSubtype', array(
'label' => 'Choose Subtype(s)',
'class' => 'form-control',
'style' => 'width:300px;height:390px;margin-bottom:20px;'
));
Can you try with BasePackage->saveAssociated ?
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
I have two models, Category and Point. The associations are defined as:
Category hasMany Point
Point belongsTo Category
I would like, when adding Points to my database, to be able to select the category it belongs to from a <select> box, along with the rest of the form data.
Where would I need to set the category list and how could I do it? And how would I produce the select box?
I assume it could be done with
$form->input('categorieslist',array('type'=>'select')); //categorieslist needs
//setting somewhere.
Also to generalize a bit:
In a View with access to the Form helper
<?php
echo $form->input( 'dataKey', array(
'type' => 'select',
'options' => array(
'key1' => 'val1',
'key2' => 'val2',
),
));
?>
The above will render a select input with two options. You can also place an empty option as the first item. Passing a value of true will simply append an empty option with a blank value to the beginning of the options rendered in the HTML.
<?php
echo $form->input( 'dataKey', array(
'type' => 'select',
'options' => array(
'key1' => 'val1',
'key2' => 'val2',
),
'empty' => true,
));
?>
You can pass a string to the 'empty' key to have it display custom text as the key field for the empty option.
<?php
echo $form->input( 'dataKey', array(
'type' => 'select',
'options' => array(
'California' => 'CA',
'Oregon' => 'OR',
),
'empty' => 'choose a state',
));
?>
One last example, you can also pre-select an option with the selected key. The value should match the value of one of the select options, not the key.
<?php
echo $form->input( 'dataKey', array(
'type' => 'select',
'options' => array(
'California' => 'CA',
'Oregon' => 'OR',
),
'empty' => 'choose a state',
'selected' => 'California',
));
?>
From the Model
Model->find( 'list', array( ... )); will always return an array formatted for use with select box options. If you pass data to your view stored in a variable with a lowercase plural model name, that is, ( $this->set( 'categories', $categories );, then you will automagically generate drop downs for related models by using the form helper in the view and passing it a data index of the same model name in singular form suffixed with "_id".
Aziz's answer at #2 is the example of that automagic kicking in.
CakePHP 1.3 Form Helper
CakePHP1.2 Form Helper
In the controller:
$categories = $this->Point->Category->find('list');
$this->set(compact('categories'));
In the view:
$form->input('category_id',array('type'=>'select'));