Use foreach in drupal array? - php

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.

Related

Autocomplete function in drupal

I have a function autocomplete like this:
function find_noreff_auto($string=NULL){
$matches = array();
db_set_active('data');
$result = db_query("SELECT * FROM reffnum where LOWER(noreff) LIKE LOWER('%%$string%%') AND journaled='0' AND noreff NOT IN (SELECT noreff from tmpreffnum) ORDER BY noreff ASC");
while ($row=db_fetch_object($result) )
{
$matches[$row->noreff.'-'.number_format($row->nominal,2)] = t($row->noreff.': '.number_format($row->nominal, 2));
}
drupal_json($matches);
drupal_set_message($matches);
}
This function:
1. If I write some character, it search from reffnum the noreff value
2. If I select one value, it give me result like this: NOREFF123 - 1.000,00
And this is the form:
$form['input']['noreff10'] = array(
'#type' => 'textfield',
'#title' => t('No Reff10'),
'#size' => 60,
'#default_value' => $noreff10,
'#description' => 'Nominal from '.$noreff10.' is '.$nominalnoreff10,
'#autocomplete_path' =>'noreff/autocomplete',
'#ahah' => array(
'event' => 'change',
'path' => ahah_helper_path(array('inputan')),
'wrapper' => 'inputan-wrapper',
'method' => 'replace',
'progress' => 'throbber',
),
'#prefix' => '<div class="s-form">', '#suffix' => '</div>',
);
I want $nominalnoreff10. What should I have to do?
$nominalnoreff10 = $noreff10['nominal']; doesn't give me the value.

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')
);

Drupal check boxes creation

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.

ZF2: how to get options for dropdown from db

I followed the tutorial. But I can find no way to populate a form select from a database like this:
// Blog/src/Blog/Form/BlogItemForm.php
$blogCategoryTable = new Model\BlogCategoryTable;
$this->add(new Element\Select('category_id',
array('label' => 'Category', 'value_options' => $blogCategoryTable->getFormChoices())
));
Does anyone have any ideas?
I use a function to retrieve the data and set it to the form:
From my factory:
$option_for_select = $this->model->getWhatEver();
$this->add($factory->createElement(array(
'name' => 'what_ever',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => $option_for_select,
),
'options' => array(
'label' => 'What ever:',
),
)));
From the model:
public function getWhatEver()
{
$sql = "SELECT something";
$statement = $this->adapter->query($sql);
$res = $statement->execute();
// set the first option
$rows[0] = array (
'value' => '0',
'label' => 'Top',
'selected' => TRUE,
'disabled' => FALSE
);
foreach ($res as $row) {
$rows[$row['triplet_id']] = array (
'value' => $row['col1'],
'label' => $row['col2'],
);
}
return $rows;
}

Categories