Drupal Form autocomplete - drupal

I wanted to have a textfield in a form that autocompletes from the database. I have been reading the tutorials and trying to get it to work but thus far not much luck. I am farely new to Drupal so I'm mostly unsure what I am doing xD
My code thus far:
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => t('Add List'),
'page callback' => 'my_module_form',
'access arguments' => array('access content'),
'description' => t('My form'),
'type' => MENU_CALLBACK,
);
// path with autocomplete function for casters
$items['caster/autocomplete'] = array(
'title' => t('Autocomplete for casters'),
'page callback' => '_caster_autocomplete',
'access arguments' => array('use autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
function my_module_form() {
return drupal_get_form('my_module_my_form');
}
function _caster_autocomplete($string) {
$matches = array();
$results = db_select('warnoun', 'w')
->fields('w', array('full_name'))
->condition('full_name', '%' . db_like($string) . '%', 'LIKE')
->execute();
// save the query to matches
foreach ($results as $result) {
$matches[$result->full_name] = check_plain($result->full_name);
}
// Return the result to the form in json
drupal_json_output($matches);
}
function my_module_my_form($form_state) {
$form['points'] = array(
'#type' => 'select',
'#title' => t('Points'),
'#required' => TRUE, // Added
'#options' => array(
0 => t('15'),
1 => t('25'),
2 => t('35'),
3 => t('50'),
),
);
$form['caster'] = array(
'#type' => 'textfield',
'#title' => t('Caster'),
'#maxlength' => 50,
'#autocomplete_path' => 'caster/autocomplete',
'#required' => TRUE,
);
$entries = db_query('SELECT id, short_name FROM factions ORDER BY id ASC');
$options = array();
foreach ($entries as $entry){
$options[$entry->id] = t($entry->short_name);
}
$form['faction'] = array(
'#type' => 'select',
'#title' => t('Faction'),
'#options' => $options,
);
// Simple Submit Button
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#required' => TRUE, // Added
);
return $form;
}
So basically there is a table called warnoun with a column full_name and it's with that content that I want to autocomplete the textfield caster.
Any idea what I'm missing/doing wrong?
Cheers

Related

Add checkboxes in fieldset

i have this fieldset and these checkboxes inside...
function repository_search_filter_form($form, &$form_state){
$form['global_fieldset_container']['global_fieldset_by_metadata'] = array (
'#type' => 'fieldset',
'#title' => t('By Metadata'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$form['global_fieldset_container']['global_fieldset_by_case_study'] = array (
'#type' => 'fieldset',
'#title' => t('By case study'),
'#collapsible' => '1',
'#weight' => '99',
'#tree' => true,
'#collapsed' => 'true',
);
$by_casestudy_options = array(
'1' =>'option1',
'2' => 'option2',
);
}
$form['global_fieldset_container']['global_fieldset_by_case_study']['bycasestudy'] = array(
'#type' => 'checkboxes',
'#options' => $by_casestudy_options
);
return $form;
}
i want in fieldset "global_fieldset_by_metadata" to add some dynamic checkboxes but in a callback function....
function ajaxforms_basic_callback($form, $form_state) {
$commands = array();
$form_filter = drupal_get_form('repository_search_filter_form');
$by_metadata_options = array(
'1' => 'Metadata1',
'2' => 'Metadata2',
);
$form_filter['global_fieldset_container']['global_fieldset_by_metadata']['bymetadata'] = array(
'#type' => 'checkbox',
'#options' => $by_metadata_options,
);
$form_filter = drupal_render($form_filter);
$commands[] = ajax_command_replace(".filter", $form_filter);
}
But the results are a empty checkbox...
PS. I tried and "checkboxes" in "#type" but i havent results in fieldset.

Drupal Custom Entity Page not found

I am actualy trying to implement my first own entity using this tutorial:
http://www.istos.it/en/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity
So far anything worked fine, but now i ran in some problem I couldnt get fixed.
After creating my new entity, I get redirected to the page "slider/(id)". But it says that the page could not be found. When I try to open the URL manualy I get the same error.
Here is my code:
he_slider.module
/**
* Implements hook_entitiy_info()
*/
function he_slider_entity_info(){
$slider_info['slider'] = array(
'label' => t('Slider Item'),
'controller class' => 'SliderController',
'views controller class' => 'EntityDefaultViewsController',
'base table' => 'slider',
'uri callback' => 'he_slider_uri',
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'sid',
),
'static cache' => TRUE,
'bundles' => array(
'slider'=> array(
'label' => 'Slider',
'admin' => array(
'path' => 'admin/structure/slider/manage',
'access arguments' => array('administer slider'),
),
),
),
'view modes' => array(
'full' => array(
'label' => t('Full Slider Item'),
'custom settings' => FALSE,
),
)
);
return $slider_info;
}
/**
* URI Callback function
*/
function he_slider_uri($slider){
return array(
'path' => 'slider/' . $slider->id,
);
}
/**
* Load the a single or multiple entities
*/
function he_slider_load($sid = NULL, $reset = FALSE){
$sids = (isset ($sid) ? array($sid) : array());
$slider = slider_load_multiple($sids, $reset);
return $slider? reset ($slider) : FALSE;
}
function he_slider_load_multiple($sids = array(), $conditions = array(), $reset = FALSE){
return entity_load('slider', $sids, $conditions, $reset);
}
/**
* Provides the Pages to administer and view the entities
*/
function he_slider_menu(){
$items['admin/content/slider/add'] = array(
'title' => 'Add Slider Item',
'page callback' => 'he_slider_add',
'access arguments' => array('create slideritem'),
);
$items['admin/structure/slider/manage'] = array(
'title' => 'Slider Administration',
'description' => 'Manage Slider Structure',
'page callback' => 'he_slider_info',
'access arguments' => array('administer slideritem'),
);
$items['slider/%slider'] = array(
'title callback' => 'he_slider_page_title',
'title arguments' => array(1),
'page callback' => 'he_slider_page_view',
'page arguments' => array(1),
'access arguments' => array('view slideritem'),
'type' => MENU_CALLBACK,
);
$items['slider/%slider/edit'] = array(
'title' => 'Slider Edit',
'title arguments' => array(1),
'page callback' => 'he_slider_page_edit',
'page arguments' => array(1),
'access arguments' => array('edit slideritem'),
'type' => MENU_CALLBACK,
);
$items['admin/content/slider/add'] = array(
'title' => 'Add Slider Item!',
'page callback' => 'he_slider_add',
'access arguments' => array('create slideritem'),
);
return $items;
}
function he_slider_permission(){
return array(
'administer slideritem' => array(
'title' => t('Administer Slider'),
'restrict access' => TRUE,
),
'view slideritem' => array(
'title' => t('View Slideritems'),
),
'edit slideritem' => array(
'title' => t('Edit Slideritems'),
)
);
}
function he_slider_info() {
return ('Welcome to the administration page for your Slideritems!');
}
function he_slider_page_title($slider){
return $slider->sid;
}
function he_slider_page_view($slider, $view_mode = 'full'){
$slider->content = array();
// Build fields content.
field_attach_prepare_view('slider', array($slider->sid => $slider), $view_mode);
entity_prepare_view('slider', array($slider->sid => $slider));
$slider->content += field_attach_view('slider', $slider, $view_mode);
return $slider->content;
}
function he_slider_field_extra_fields() {
$return = array();
$return['slider']['slider'] = array(
'form' => array(
'title' => array(
'label' => t('Title'),
'description' => t('Slider Title'),
),
),
);
return $return;
}
/**
* Implements the slider add form, where we are able to create our new entities
*/
function he_slider_add() {
$slider = (object) array (
'sid' => '',
'type' => 'slider',
'title' => '',
);
return drupal_get_form('he_slider_add_form', $slider);
}
function he_slider_add_form($form, &$form_state, $slider) {
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Note'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
field_attach_form('slider', $slider, $form, $form_state);
return $form;
}
/**
* Implements the Entitiy Edit form
*/
function he_slider_page_edit($slider) {
return drupal_get_form('he_slider_add_form', $slider);
}
/**
* Validates the Entity Add form
*/
function he_slider_add_form_validate($form, &$form_state) {
$slider_submission = (object) $form_state['values'];
field_attach_form_validate('slider', $slider_submission, $form, $form_state);
}
function he_slider_add_form_submit($form, &$form_state) {
$slider_submission = (object) $form_state['values'];
field_attach_submit('slider', $slider_submission, $form, $form_state);
$slider = he_slider_save($slider_submission);
$form_state['redirect'] = "slider/$slider->sid";
}
function he_slider_save(&$slider) {
return entity_get_controller('slider')->save($slider);
}
/**
* Implements hook_views_api().
*/
function he_slider_views_api() {
return array(
'api' => 3,
'path' => drupal_get_path('module', 'slider') . '/views',
);
}
/**
* Implements hook_form_alter().
*/
function he_slider_form_alter(&$form, &$form_state, $form_id) {
if($form_id=='_slider_add_form'){
$form['submit']['#weight'] = 99;
}
}
he_slider.controller.inc:
class SliderController extends DrupalDefaultEntityController {
public function save($slider) {
drupal_write_record('slider', $slider);
field_attach_insert('slider', $slider);
module_invoke_all('entity_insert', $slider, 'slider');
return $slider;
}
}
The problem is here:
$items['slider/%slider'] = array(
Drupal's menu system will look for a function named slider_load(), whereas your entity load function is named he_slider_load(). This causes the router to bail out and throw a 404.
To fix it, simply change that line to
$items['slider/%he_slider'] = array(
And clear your caches.

Drupal 7 - Submit function not triggered on theme table

I want to be able to select items from two select lists and then submit (which will take me to another form.
The following is the code I have however the submit function (submit_function) does not appear to get triggered (it just refreshes the form). What am I doing wrong?
function myfunction($form, &$form_state)
{
$output = drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);
$header = array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
);
$rows = array(
array(
'columnone' => array(
'data' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
),
'columntwo' => array(
'data' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
),
'columnthree' =>array(
'data' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
)
),
),
);
$output['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#weight' => 2,
);
return $output;
}
That is quite normal, you are mixing form elements with static renderable elements. A drupal_get_form function expects a form build.
What you need to create is your custom form theme table which outputs a theme within a form build. Here is some sample code that could help you further:
function YOURMODULE_theme()
{
// define a table form theme
return array(
'YOURMODULE_table_form' => array(
'render element' => 'element'
),
);
}
function theme_YOURMODULE_table_form($vars)
{
$element = $vars['element'];
$form_keys = false;
$rows = array();
// loop through each row form elements
foreach (element_children($element) as $key) {
if (!$form_keys) {
$form_keys = array();
// retrieve the form keys for each row
foreach (element_children($element[$key]) as $f_key) {
$form_keys[$f_key] = isset($element[$key][$f_key]['#title'])
? $element[$key][$f_key]['#title']
: '';
}
}
$row = array();
foreach ($form_keys as $fieldkey => $fieldname) {
// render each field in a separate row
$row[] = array(
'data' => drupal_render($element[$key][$fieldkey])
);
}
$rows[] = $row;
}
// return a build for the table
return theme('table', array(
'header' => $vars['element']['#header'],
'rows' => $rows,
'empty' => isset($vars['element']['#empty'])
? $vars['element']['#header']
: '',
));
}
And the form using your logic:
function myfunction($form, &$form_state)
{
$form['table'] = array(
'#theme' => 'YOURMODULE_table_form',
'#header' => array(
'columnone' => t('Column 1'),
'columntwo' => t('Column 2'),
'columnthree' => t('Column 3'),
),
'#tree' => true,
);
$form['table'][0] = array(
'columnone' => array(
'#type' => 'select',
'#options' => columnoneoptions(),
),
'columntwo' => array(
'#type' => 'select',
'#options' => columntwooptions(),
),
'columnthree' => array(
'#type' => 'submit',
'#value' => t('Add'),
'#weight' => 45,
'#submit' => array('submit_function'),
),
);
return $form;
}

My Node Type wont Show It's Fields

I am trying to create my first drupal module that creates a simple node type wcNames. This node type has two fields, firstname & lastname.
I could get my module create the DB table for node type and add it in node_type table, but when I open node/add/wc-name fields firstname and lastname don't appear.
Below is my code. Please suggest.
<?php
// wc_name.install file
/*
* hook_schema Implementation: Creates the DB and it's fields
*/
function wc_name_schema(){
$schema['wc_name_names'] = array(
'fields' => array(
'nmid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
'firstname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
'lastname' => array('type' => 'varchar', 'length' => 50, 'not null' => FALSE),
),
'primary key' => array('nmid'),
'unique keys' => array(),
'indexes' => array(
'nmid' => array('nmid'),
),
);
return $schema;
}
//function wc_name_install(){ } // Use this function to set variables for the module.
function wc_name_uninstall(){
//unset variables if any set
// Delete all wc_name nodes
db_delete('node')->condition('type', 'wc_name')->execute();
// Delete all wc_name tables
db_drop_table('wc_name_names');
}
?>
<?php
// wc_name.module
/*
* Implementation of _node_info(): define node
*/
function wc_name_node_info(){
return array(
'wc_name' => array(
'name' => t('wcName'),
'base' => 'wc_name',
'base' => 'page',
'description' => t("A smaple module to save names."),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => FALSE,
)
);
}
function wc_name_menu() {
$items = array();
$items['wc_name'] = array(
'title' => 'wcNames',
'page callback' => 'wc_name',
// 'access arguments' => array('access wcNames'),
);
}
?>
<?php
// wc_name_form.inc
function wc_name_form($node, &$form_state){
// Add fields
$form['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['firstname'],
);
$form['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => FALSE,
'#default_value' => $node->wc_name['lastname'],
);
return $form;
}
?>
What am I missing?
Try this:
function createTextFieldByName($type, $fieldname, $fieldlabel)
{
$field = field_info_field($fieldname);
if (empty($field)) {
$field = array(
'field_name' => $fieldname,
'type' => 'text',
'entity_types' => array('node'),
'translatable' => TRUE,
);
$field = field_create_field($field);
}
$instance = field_info_instance('node', $fieldname, $type);
if (empty($instance)) {
$instance = array(
'field_name' => $fieldname,
'entity_type' => 'node',
'bundle' => $type,
'label' => $fieldlabel,
);
$instance = field_create_instance($instance);
return $instance;
}
return null;
}
$type =
array(
'type' => 'MY_TYPE',
'name' => t('NAME'),
'base' => 'node_content',
'description' => t("DESCRIPTION"),
'custom' => 1,
'modified' => 1,
'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);
createTextFieldByName($type,'firstname','First name');
createTextFieldByName($type,'lastname','Last name');

how to load database content to dropdown options (select)

i'm still working on my own drupal 7 module, and i'm having some trouble. I'm trying to load database content to dropdown option (select), i have read and write the same code from drupal example, but my database still not loading, only empty option.
what i'm asking is there anything wrong on my code or is there any faster way to load database to dropdown option other than the drupal example???
here the code i'm working on
function prod_entry_load($entry = array()) {
$select = db_select('aa_1122','aa');
$select->fields('aa');
foreach ($entry as $field => $value) {
$select->condition($field, $value);
}
return $select->execute()->fetchAll();
}
function prod(){
return drupal_get_form('prod_form');
}
function prod_form($form_state){
$form = array(
'#prefix' => '<div id="updateform">',
'#suffix' => '</div>',
);
$entries = prod_entry_load();
$keyed_entries = array();
if (empty($entries)) {
$form['no_values'] = array(
'#value' => t("No entries exist in the table dbtng_example table."),
);
return $form;
}
foreach ($entries as $entry) {
$options[$entry->no] = t("#no: #name ", array('#no' => $entry->no, '#name' => $entry->name));
$keyed_entries[$entry->no] = $entry;
}
$default_entry = !empty($form_state['values']['no']) ? $keyed_entries[$form_state['values']['no']] : $entries[0];
$form_state['entries'] = $keyed_entries;
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#ajax' => array(
'callback' => 'ajax_alert',
),
);
return $form;
}
function prod_form_update_callback($form, $form_state) {
$entry = $form_state['entries'][$form_state['values']['no']];
foreach (array('name') as $item) {
$form[$item]['#value'] = $entry->$item;
}
return $form;
}
You've just forgotten to add the #options key to your select element, the code should read like this:
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#options' => $options, // This is the bit that was missing
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
You could shorten your query/options code slightly using a combination of string concatenation in MySQL and the db fetchAllKeyed() method:
$query = db_select('aa_1122', 'aa')->fields('aa', array('no'));
$query->addExpression("CONCAT(no, ': ', name)", 'display');
$options = $query->execute()->fetchAllKeyed();

Resources