Drupal check boxes creation - php

I have the form in drupal7.
What i need is: i have category and sub category . I have to list these in checkboxes like
I used the code as
$form['rate_the_room']['talent'] = array(
'#prefix'=>'<h1>category:</h1>',
'#type' => 'checkboxes',
'#options' => $sub_tal,
);
Here $sub_tal is an array. If it is the single dimensional array it works fine. Here how to pass an array(The category , sub categories are came from db). How to maintain this structure with this code.
Please help me thanks.

Is there any particular reason why these all need to be in one form element? If your data is set up properly, you can simply loop through them and create elements in a somewhat organized fashion.
function my_test_form($form_state) {
// Assuming you have your data in a format like this
$categories = array(
'cat1' => array(
'#title' => 'category 1',
'sub1' => 'Subcat1',
'sub2' => 'Subcat2',
),
'cat2' => array(
'#title' => 'category 2',
'sub21' => 'Subcat21',
'sub22' => 'Subcat22',
),
'cat3' => 'category 3',
);
$elements = array();
foreach ($categories as $cat => $data) {
// If multidimensional, create parent and loop through children
if (is_array($data)) {
$elements[] = array(
'#type' => 'checkbox',
'#title' => $data['#title'],
'#return_value' => $cat,
);
foreach (element_children($data) as $subcat) {
$elements[] = array(
'#type' => 'checkbox',
'#title' => $data[$subcat],
'#attributes' => array(
'style' => 'margin-left: 2em',
),
'#return_value' => $cat . '-' . $subcat,
);
}
}
// Else, just create top level
else {
$elements[] = array(
'#type' => 'checkbox',
'#title' => $data,
'#return_value' => $cat,
);
}
}
// Group all of these elements together. They'll be submitted into the same array.
$form['categories'] = $elements;
$form['categories']['#tree'] = TRUE;
$form['categories']['#prefix'] = '<div style="font-weight:bold" class="label">' . t('Checkboxes title') . ':</div>';
$form['submit'] = array(
'#value' => t('Submit me'),
'#type' => 'submit',
);
return $form;
}
function my_test_form_submit($form, &$form_state) {
$submitted_values = array_filter($form_state['values']['categories']);
}
Renders as:
And when the form is submitted, assuming some checkboxes were checked, $submitted_values looks like this:
array('cat2', 'cat2-sub21', 'cat2-sub22')
You can change the values of the checkboxes submitted to the submit handler by changing the #return_value attribute that I set on each checkbox above.
The submitted values are grouped together not only because they are all within the $form['categories'] section, but also because #tree is set to TRUE.

Related

Use foreach in drupal array?

I want to create a statistics page in a Drupal 7 module. But for that I actually need to do a foreach inside an array.. I think this is not possible but I'm not 100% sure about this.
this is my code at the moment (doesn't work, concatenated wrong etc..)
Does anyone know if this is possible and can give a little example how to do it
My code:
$id = $_GET['id'];
$query = db_query('SELECT * FROM push_notifications_messages WHERE app_id = :app_id', array(':app_id' => $id));
$qCount = db_query('SELECT * FROM push_notifications_messages WHERE app_id = :app_id', array(':app_id' => $id))->rowCount();
$form['table'] = array(
'#theme' => 'table',
'#header' => array(t('Message'), t('Device'), t('Date')),
'#rows' => array(
foreach($query as $result) {
for($i = 1; $i <= $qCount; $i++) {
echo "'r" . $i . "'" . => array(
"'c1'" . => array(
'#type' => 'textfield',
'#title' => t('#message', array('#message' => $result['msg_message']))
),
"'c2'" . => array(
'#type' => 'textfield',
'#title' => t('#device', array('#device' => $result['msg_device']))
),
),
}
}
),
);
Thanks in advance!!
Just extract your foreach loop out of the array definition and then assign the values after it like this:
<?php
$form['table'] = array(
'#theme' => 'table',
'#header' => array(t('Message'), t('Device'), t('Date')),
'#rows' => array(),
);
foreach($query as $result) {
for($i = 1; $i <= $qCount; $i++) {
$form['table']["#rows"]["'r$i'"] = array(
"'c1'" => array(
'#type' => 'textfield',
'#title' => t('#message', array('#message' => $result['msg_message']))
),
"'c2'" => array(
'#type' => 'textfield',
'#title' => t('#device', array('#device' => $result['msg_device']))
),
);
}
}
?>
You should not use echo,foreach kind of PHP codes inside a drupal form builder code. Without giving any comment I would like to share this with you. Hope it will help you better than me.

Count textfields filled to populate options in a select input in Drupal 7 form

I would like to be able to count the number of text inputs that have been filled and use the result to create a drop down with the options 0-[count returned]. I am using the
ajax_command_replace function in Drupal 7 but open to suggestions of any other method.
I have a test which does count the inputs filled and displays the result but I cannot figure out how to then use this to populate a select.
Any help much appreciated.
for the form elements.
$array = array_fill(0,5,'');
$form['test'] = array(
'#type'=> 'fieldset',
'#title' => 'TEST',
);
$form['test']['value']['#tree'] = TRUE;
foreach ($array as $key => $value) {
$form['test']['value'][$key] = array(
'#type' => 'textfield',
'#ajax' => array(
'callback' => 'test_callback',
),
);
}
$test = count(array_filter($array));
$form['test']['count'] = array(
'#suffix' => "<div id='testcount'>filled inputs = $test</div>",
);
and the ajax callback
function test_callback($form, $form_state){
$text = count(array_filter($form_state['input']['value']));
$commands = array();
$commands[] = ajax_command_replace("#testcount", "<div id='testcount'>filled inputs = $text</div>");
return array('#type' => 'ajax', '#commands' => $commands);
}
Thanks
This seems to be working for me now, same method but using the render() function to return an updated form element from within the callback. I hope it helps someone else.
$array = array_fill(0,5,'');
$form['test'] = array(
'#type'=> 'fieldset',
'#title' => 'TEST',
);
$form['test']['value']['#tree'] = TRUE;
foreach ($array as $key => $value) {
$form['test']['value'][$key] = array(
'#type' => 'textfield',
'#ajax' => array(
'callback' => 'test_callback',
),
);
}
$options = range(count(array_filter($array)),0,1);
$form['test']['count'] = array(
'#type'=> 'select',
'#options' => $options,
'#prefix' => '<div id="testcount">',
'#suffix' => "</div>",
);
Callback
function test_callback($form, $form_state){
$text = count(array_filter($form_state['input']['value']));
$default = $form_state['input']['count'];
$options = range($text,0,1);
$form['test']['count'] = array(
'#type'=> 'select',
'#options' => $options,
'#prefix' => '<div id="testcount">',
'#suffix' => "</div>",
'#default_value' => $default,
);
$commands = array();
$commands[] = ajax_command_replace("#testcount", render($form['test']['count']));
return array('#type' => 'ajax', '#commands' => $commands);
}

Drupal pager on table with sort and select and search not working

I have a query which I want shown as a Drupal tableselect with sorting and pagination and search term which is memorized in the $_SESSION. The problem is that the pagination is not working.
My code looks kinda like this:
//build the header row (except the checkbox)
$header = array(
'status' => array('data' => t('Status')),
'name' => array('data' => t('Product name'), 'field' => 'p.name'),
'actions' => array('data' => t('Actions'))
);
//do the query for the data
$query = db_select('my_products', 'p');
$query->addField('p', 'pid');
$query->addField('p', 'name');
$query->addField('p', 'status');
//in case there is a search term then filter the table
if(isset($_SESSION['search_term_product'])) {
$query->condition('p.name', '%' . db_like($_SESSION['search_term_product']) . '%', 'LIKE');
}
//add a pager to the resulting data and a sorter
$query->extend('PagerDefault')
->limit(10);
->extend('TableSort')
->orderByHeader($header);
$result_set = $query->execute();
//structure the data accordingly
$rows = array();
$default_value = array();
foreach($result_set as $product) {
$default_value[$product->pid] = $product->status == 1 ? TRUE : FALSE; //ticked or not tiked
$rows[$product->pid] = array(//array key is needed for form submission
'status' => $product->status == 1 ? t('Active') : t('Not active'),
'name' => array(
'data' => array(
'#type' => 'link',
'#title' => $product->name,
'#href' => $base_url . '/' . $product->name . '/edit'
)
),
'actions' => array(
'data' => array(
'#type' => 'link',
'#title' => 'Delete',
'#href' => $base_url . '/' . $product->name . '/delete'
)
)
);
}
//configure the table
$form['products'] = array
(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
'#empty' => t('No products found'),
'#multiple' => TRUE, //TRUE -> checkboxes FALSE-> radio buttons
'#default_value' => $default_value,
'#markup' => theme('pager')
);
$form['submit'] = array
(
'#type' => 'submit',
'#value' => t('Change status'),
);
return $form;
I tried lots of solutions and searched the web extensively but I don't know why the pagination isn't working. This code just shows all the result like my pagination code wasn't even there.
Any suggestions?
Edit: In my original code I have a few joins.
After many many tries I managed to solve it. I think there's a problem if you add the ->extend('PagerDefault') after a join. Anyway all you have to do is change
db_select('my_products', 'p');
to
db_select('my_products','p')->extend('PagerDefault')->extend('TableSort');
$query->extend('PagerDefault')
->limit(10);
->extend('TableSort')
->orderByHeader($header);
to
$query->limit(10)
->orderByHeader($header);
delete the line with '#markup' => theme('pager') and before return $form add
$form['pager'] = array(
'#markup' => theme('pager')
);

merge two forms fields in drupal

I am merging the form with another form contains table based. Table contains the list with checkbox, after filling the form fields, checkboxes are selected and submitted.
When i write this code, Two forms with same id is generated how should i merge the two functions in one form.
function add_newHardware() {
$output = drupal_get_form('add_new_form');
return $output;
}
function add_new_form(&$form_state) {
$form['#attributes']['id'] = 'myform';
$form['device'] = array(
'#type' => 'fieldset',
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['device']['type'] = array(
'#type' => 'select',
'#options' => listType(),
);
$form['device']['title'] = array(
'#type' => 'item',
'#value' => '<h4>2. Enter Information</h4>',
);
$form['table'] = array(
'#type' => 'item',
'#value' => drupal_get_form('selectList'),
);
}
function selectList() {
$form['#attributes']['id'] = 'myform';
......
$output .= theme('table', $header, $rows);
$output .= drupal_render($form);
return $output;
}

Drupal Table of form elements

I am trying to create a table in the config page for my module. I need the table to include some form elements, Checkbox and textfield. I want to structure the table like so.
Enable | Name | Int
Enable being the checkbox, name being a standard text value and int being the textfield. I want to be able to check a box next to a name, type in a value and then have it save when it submits. Currently I am doing this in the .admin.inc. I have actually been able to make the table and have the elements in it. However I cant put values in or get them out.
How I am creating the rows
foreach($rows as $row){
$form['table']['intvalue'] = array(
'#type' => 'textfield',
'#default_value' => 100,
'#size' => 8,
);
$form['table']['enable'] = array(
'#type' => 'checkbox',
'#default_value' => TRUE,
);
$rows[] = array(drupal_render($form['table']['enable']), $name, drupal_render($form['table']['intvalue']));
}
And this is how I am displaying the table
$table = theme('table', array(
'header' => $header,
'rows' => $rows,
'id' => 'table-articles',
'class' => 'articles',
));
$form['table'] = array(
'#type' => 'item',
'#title' => t('Table'),
'#markup' => $table,
'#weight' => -2,
);
Any idea?

Categories