Drupal 7 - Populate Drop Down select from DB in Form API - drupal-7

I am still new to PHP, and even newer to Drupal's Form API. I'm simply trying to populate a drop down select from the database. I think the issue stems from my lack of a deep understanding of how to work with multidimensional arrays. Any help is sincerely appreciated.
My code is currently:
//Query DB for Rows
$query = db_select('hp_education_years');
$query->fields('hp_education_years', array('id', 'years',));
$query->orderBy('years', 'ASC');
$results = $query->execute();
//define rows
$options = array();
foreach ($results as $result) {
$options[$result->id] = array(
$result->years,
);
}
$form['education']['year'] = array(
'#type' => 'select',
'#title' => t('Year'),
'#options' => $options,
'#states' => array(
'visible' => array(
':input[name="data_set"]' => array('value' => 'education'),
),
),
);
This returned a populated list, but displays the year's ID in bold as well as the year (2008 for example).
How can I get the dropdown just to display the year, not the year ID in bold, and then the year. It seems like $option is just a level higher than I want it to be? if that makes sense?
Many thanks in advance.

Try changing
//define rows
$options = array();
foreach ($results as $result) {
$options[$result->id] = array(
$result->years,
);
}
to
//define rows
$options = array();
foreach ($results as $result) {
$options[$result->id] = $result->years;
}
If you look at the example from Drupal's Form API, you'll see that the Options values should be just the string value and not an array.

Related

Checkbox values are boolean instead of machine name of menu link in custom module drupal

I am newbie in drupal and i am developing a custom module.Actually i am listing all drupal menu's and their children using fieldset and checkboxes against each menu in a loop.
Here what is i have done so far.
function hide_menu_item_configuration_form($node, &$form_state){
$form = array();
$form['markup'] = array(
'#type'=>'markup',
'#markup'=>t('<p>Select a menu.</p>'),
);
$menus = menu_get_menus($all = TRUE);
foreach ($menus as $key => $value) {
$form['menus'][$value] = array(
'#type'=>'fieldset',
'#title'=>t($value),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$menu_items = menu_load_links($key);
foreach ($menu_items as $key => $values) {
$form['menus'][$value][$values['link_title']] = array(
'#type' => 'checkbox',
'#title' => t($values['link_title']),
'#' => t($values['link_title']),
'#default_value' => 1
);
}
}
$form['config_submit'] = array(
'#type'=>'submit',
'#value'=>'Save configuration',
);
return $form;
}
function hide_menu_item_configuration_form_submit(&$form, &$form_state) {
//here i see values
dsm($form_state);
}
Now what the problem is that on form submit,i am getting boolean value against each menu link like 0 or 1 .In this case,i can't gues which link was checked or not.Because of 0 or 1 which doesn't indicate anything.But i want to get menu machine name and link machine name.
I am stuck here.
Can you please guys help or suggest me some other way to complete this thing?
Please help.
pls changes your code first build the options array using the foreach loop you are running
$options = array();
$menu_items = menu_load_links($key);
foreach ($menu_items as $key => $values) {
$options[$values['link_title']] = $values['link_title'];
}
$form['name']=array(
'#type'=>'checkbox',
'#title'=>'any title',
'#description' => 'any Description',
'#options' => $options,
);

Populating #options, #header for tableselect in ajax callback function

What I am trying to do is display a table with checkboxes on the press of a button by ajax. The table should be initially hidden and get populated on the fly by a function call.
If initially I load $options1 with some dummy values , then after ajax call it throws in an error saying-
Notice: Undefined index: red in theme_tableselect() (line 3285 of
D:\wamp\www\drupal7\includes\form.inc).
where 'red' is the index of a dummy row value and #options don't get populated with the new values. What is the way to get this working ?
Here is the code for the form-
$form['mltag_new']['tag'] = array(
'#type' => 'button',
'#value' => t("Suggest Tags"),
'#ajax' => array(
'callback' => 'mltag_suggest_tags_ajax',
'wrapper' => 'mltag_suggest_tags_table_div',
'effect' => 'slide',
),
);
$options1 = array(); //initial dummy values
$options1['red']['tag'] = "A red row";
$options1['red']['chi'] = "A red row";
$form['mltag_new']['myselector'] = array (
'#type' => 'tableselect',
'#title' => 'My Selector',
'#header' => $header,
'#options' => $options1,
'#prefix' => '<div id="mltag_suggest_tags_table_div">',
'#suffix' => '</div>',
);
return $form;
and the Ajax callback looks something like this-
function mltag_suggest_tags_ajax($form, $form_state) {
//$content has some content
//pass the content to a function
include_once 'includes/content_tag.inc';
$tags = mltag_content_tag($content, variable_get('algo_type'), 20);
if (empty($tags)) {
$output .= t('Content is insufficient to generate Tags using this algorithm. <br>Please choose other algorithm from Settings Page.');
$form['mltag_new']['sample_text']['#markup'] = $output;
return $form['mltag_new']['sample_text'];
}
else {
$algo = variable_get('algo_type');
if ($algo == 1) {
$header = array(
'tag' => t('Tag'),
'frequency' => t('Frequency'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'frequency' => $value,
);
}
}
elseif ($algo == 2) {
$header = array(
'tag' => t('Tag'),
'chi' => t('Chi Square Value'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'chi' => $value,
);
}
}
$form['mltag_new']['myselector']['#header'] = $header;
$form['mltag_new']['myselector']['#options'] = $options;
return $form['mltag_new']['myselector'];
}
}
I replied to your post on Drupal.org about how I'm working on a somewhat similar problem. Try adding
$form['mltag_new']['myselector'] =
form_process_tableselect($form['mltag_new']['myselector']);
just before your return. Hopefully that helps you more than it did me. Beware that the #options just get rendered when the block reloads from the ajax, but the original $form object doesn't seem to be aware.
I know that this is a few years later, but I found this while searching for my own solution:
The tableselect module creates checkboxes in the $ form that have to be removed. in the example above, they would be in $form['mltag_new']['myselector'] with keys equal to the original $option1 in your original code. If you unset those, then call
$form['mltag_new']['myselector'] = form_process_tableselect($form['mltag_new']['myselector']);
before your return, it will eliminate the dummy rows.

Drupal 7 theme(''pager') -> table get's rendered but without Pager?

I have a table with data from the database, I would like it to have a Pager, I have all the code from an example (of buildamodule.com) among other sites, and my table get's rendered, but it doesn't generate a pager, although I have more rows then the limit:
the function:
function get_loyaltycodes(){
$headers = array(
array(
'data' => t('Code')
),
array(
'data' => t('Info')
),
array(
'data' => t('Points')
),
array(
'data' => t('Consumed by')
),
);
$limit = variable_get('codes_per_page',5);
$query = db_select('loyalty_codes','lc');
$query -> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> extend('PagerDefault')
-> limit($limit);
//to see all codes for a certain amount of points, just append the number of points to the URL
$arg = arg(2);
if($arg != '' && is_numeric($arg))
{
$query->condition('points', $arg);
}
// Fetch the result set.
$result = $query->execute();
$rows = array();
// Loop through each item and add to the $rows array.
foreach ($result as $row) {
$rows[] = array(
$row->code,
$row->info,
$row->points,
$row->uid,
);
}
// Format output.
$output = theme('table', array('header' => $headers, 'rows' => $rows)) . theme('pager');
return $output;
the $limit variable is set to 5 in the settings form, and it is 5 in the database too.
Anybody who has any idea in why the pager is not showing? perhaps something in the formatting off the output?
Help is very much appreciated!
apparently I can't log in right know because I'm behind a firewall, anyway I seem to have fixed it, stupid mistake though:
the ‘->extend(‘PagerDefault’) extension in the query had to be the first function in the daisy chain. If not there is no error but the function seems to not be called.
$query = db_select('loyalty_codes','lc')
->extend('PagerDefault')
-> fields('lc',array('code','info','points','uid'))
-> orderBy('lc.info','ASC')
-> limit(5);//$limit);

how to tell cakephp to use function index($type) to just go to the index page?

I have this application that directs users to Types of attractions with this function:
public function index($type=null) {
$this->set('title','What to do when you visit Gulf Shores');
$this->paginate['Attraction']=array(
'limit'=>9,
'order'=>array('Attraction.id'=>'asc'),
'conditions'=>array(
'active'=>1,
'attr_type'=>$type
)
);
$c=$this->paginate('Attraction');
$this->set('attractions', $c);
}
and it works great, but I'd like users to also be able to go to a front page /attractions/ that doesn't filter out by attr_type. This function shows zero results (as obviously $type still = null) for the front page. Is there a step I'm missing or must I have a view.ctp file and function in my controller?
You could use an if statement to determine the conditions:
public function index($type = null) {
$this->set('title', 'What to do when you visit Gulf Shores');
$conditions = array(); //create $conditions outside of the if statement
if ($type) { //if $type is equal to anything other than null or 0
$conditions = array(
'active' => 1,
'attr_type' => $type
);
} else {
$conditions = array(
'active' => 1
);
}
$this->paginate['Attraction'] = array(
'limit' => 9,
'order' => array('Attraction.id' => 'asc'),
'conditions' => $conditions
);
$c = $this->paginate('Attraction');
$this->set('attractions', $c);
}
It's not actually necessary to create $conditions outside of the if statement in PHP but it is in a lot of other programming languages because of scope.
If you create a variable inside a if statement is it available outside the if statement?

Virtual field in 'fields' find condition - Cakephp

I have a Student model with a virtual field:
var $virtualFields = array(
'full_name' => 'CONCAT(Student.fname, " ", Student.lname)'
);
I am doing a find operation to fetch specific fields using 'fields':
$this->Student->find('all', array('fields' => array('Student.fname','Student.lname')));
For some reason, the virtual field is not being created after finding the records. I tried adding Student.full_name but of course it gives an unknown column error in mysql.
Any ideas?
You can't specify in fields a virtual field you need to call it without the fields option so it bring it with the results... you may wanna read the examples in the cookbook
calling all fields is one option another one is to call the field in the fields option, something like this
$this->Student->find('all', array('fields' => array(
$this->student->virtualFields['full_name'].'AS Student__full_name',
'Student.fname','Student.lname')
));
what about placing a method in your app_model.php like so:
/**
* combine virtual fields with fields values of find()
* USAGE:
* $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
* #param array $virtualFields to include
*/
public function virtualFields($fields = array()) {
$res = array();
foreach ((array)$fields as $field) {
//TODO: if key numeric => value sql!
//TODO: allow combined/other models via Model.field syntax
$sql = $this->virtualFields[$field];
$res[] = $sql.' AS '.$this->alias.'__'.$field;
}
return $res;
}
and then use it like so:
$this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')))
));
or so:
$fields = $this->Model->virtualFields('full_name');
$fields = am($fields, 'status', 'created');
$this->Model->find('all', array('fields' => $fields));
));
On the CookBook:
http://book.cakephp.org/2.0/en/models/virtual-fields.html
It says that you can use it like:
Model:
public $virtualFields = array(
'name' => 'CONCAT(User.first_name, " ", User.last_name)');
Controller or View:
$results = $this->User->find('first');
Result:
array(
[User]
[first_name] => 'Mark',
[last_name] => 'Story',
[name] => 'Mark Story',
//more fields.
)
So you can use it just like this:
$this->set('list_fields', $this->User->find('list',
array('fields' => array('first_name', 'last_name', 'name'),
'recursive' => -1, 'condition' => ...)));

Resources