I'm creating my very first Drupal module (Drupal 7, btw) and I'm almost done with it. There is one last thing and that is that I need to get the values from multiple checkboxes.
My module list certain nodes and each of them gets a checkbox using a foreach $nid. All using the Form API.
Now, when the form is submitted, only one (1) value is returned - and as of now, not even the one that I check, but the last nodes ID.
Perhaps it is because each new value replaces the previous(?). Or something is wring with my code. Someone in the IRC channel told be that the forms checkbox returns an array of the values, but I'm trying to use foreach of that value, without any success.
What could be the problem? Here is my code - shorted down.
function my_module_cmp($a, $b) {
$a = (array) $a;
$b = (array) $b;
return strcmp($a['name'], $b['name']);
}
function my_module_form() {
$url = taxonomy_get_term_by_name(arg(1));
foreach($url as $term) {
$tid = $term->tid;
}
$term = taxonomy_term_load($tid);
$name = taxonomy_term_title($term);
$terms = taxonomy_get_tree(3,0,1);
usort($terms, "my_module_cmp");
$counter = 0;
$result = taxonomy_select_nodes($tid);
foreach($result as $nid) {
$form[$nid] = array (
'#type' => 'fieldset'
);
// title
$form[$nid]['title'] = array (
'#markup' => '<div class="title"><a href="/'.$nid.'">' . $node->title . '</a></div>',
);
// checkbox
$form[$nid]['company'] = array (
'#type' => 'checkbox',
'#title' => t('Check the nodes balbla'),
'#title_display' => 'attribute',
'#return_value' => $nid,
'#default_value' => 0,
'#prefix' => '<a class="checkbox">Skicka förfrågan till företaget >>',
'#suffix' => '</a>',
);
$counter++;
}
return $form;
}
function my_module_form_validate($form, &$form_state) {
// Validate that a company has been checked, at all
$valid_company = $form_state['values']['company'];
if (!$valid_company) {
form_set_error('company', 'Forgot to check something');
}
}
function my_module_form_submit($form, &$form_state) {
$company = $form_state['values']['company'];
drupal_set_message('<pre>'.print_r($form_state['values'], 1).'</pre>'); // Check out the values
foreach ($company as $nid) {
// Get the node from nid
$node = node_load($nid);
// Get the author of that node
$user = user_load(array('uid' => $node->uid));
drupal_set_message(t('DEBUG node:'.$nid.', user: '.$user->name.','.$user->mail.'')); // TEST
// Check if the mail has been sent and show a message based on that
if (drupal_mail('my_module', 'token', $user->mail, language_default(), $message, $from, TRUE)) {
drupal_set_message(t('Offert been sent %name',array('%name' => $user->name)));
}
else {
drupal_set_message(t('Error'));
}
}
}