Autofill fields in drupal7 - drupal-7

I'm trying to autofill text fields after selecting an item from select list. What I mean is: first I want user to choose an item from select list and then there will be 3 more text fields and I want to give them distinct values based on which was selected.

You need to use Drupal "Ajax framework". Please prepare your fields in hook_form_alter function.
function hook_form_alter(&$form, &$form_state, $form_id) {
if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
$form['select_field'] = array(
'#ajax' => array(
'callback' => '_mymodule_ajax_example_simplest_callback',
'wrapper' => 'replace_textfield_div',
),
);
// This entire form element will be replaced with an updated value.
$form['textfield_to_autofill'] = array(
'#prefix' => '<div id="replace_textfield_div">',
'#suffix' => '</div>',
);
}
}
function _mymodule_ajax_example_simplest_callback(&$form, $form_state) {
// The form has already been submitted and updated. We can return the replaced
// item as it is.
$commands = array();
if($form_state['values']['select_field'][LANGUAGE_NONE][0]['value'] == "some_value"){
$form['textfield_to_autofill'][LANGUAGE_NONE][0]['value']['#value'] = "some_value";
$commands[] = ajax_command_replace("#replace_textfield_div", render($form['textfield_to_autofill']));
}
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);
}
Here helping link for ajax framework.

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

Updating and deleting data in D7

I have made a form in D7 using form API, registered some users and retrieved their registered data from database;now what i want is to add an edit and a delete link in front of every row in the retrieved table;i have done that in PHP but how to implement same in Drupal?;anybody having any idea how to do that?
My retrieval code is:
function form_data_menu() {
$items['formdata'] = array(
'title' => 'Form Data',
'page callback' => 'form_data_form',
'access callback' => TRUE,
);
return $items;
}
function form_data_form()
{
$results = db_query('SELECT * FROM {drupal}');
$header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'));
$rows = array();
foreach($results as $result) {
$rows[] = array(
$result->id,
$result->name,
$result->college,
$result->education,
$result->percentage,
$result->application,
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}
I can add links though but the main problem is how to run update and delete queries in D7?
Any help will be appreciated. Thank you!
Start with the example module "dbtng_example.module".
https://www.drupal.org/project/examples
This will give an example of how to set up a module to save to the database. I used this recently to create a custom module to save data to a new database table within drupal. To figure out how to set up the hook_schema, you can look at ".install" files within the drupal core and contributed codebase.
Then to create an edit or delete link, you need to alter your hook_menu to pass in the unique id for that element:
$items['admin/structure/nates-custom-page/update/%'] = array(
'title' => 'Update entry',
'page callback' => 'drupal_get_form',
'page arguments' => array('nates_module_form_update', 5),
'weight' => -5,
'access arguments' => array('administer DFP'),
);
$items['admin/structure/nates-custom-page/delete/%'] = array(
'title' => 'Delete entry',
'page callback' => 'drupal_get_form',
'page arguments' => array('nates_module_form_delete', 5),
'access arguments' => array('administer DFP'),
);
Above is an example where I added the argument (indicated by the percentage sign in the array key, ("%"), that will represent the unique id for that item I want to edit or delete.
Then alter the edit form to load the item you want to edit by the id.
And add a delete form.
Here's an example of a delete form:
function nates_module_form_delete($form, &$form_state) {
$entry = nates_module_entry_load_by_pid(arg(5));
$form = array();
$form['pid'] = array(
'#type' => 'value',
'#value' => arg(5),
);
$output = "";
foreach($entry as $key => $value) {
$output .= "<p><strong>$key</strong>: $value</p>";
}
$form['markup'] = array(
'#type' => 'markup',
'#markup' => $output,
);
return confirm_form(
$form,
t('Are you sure you want to delete this item? '),
'example/list',
t('This action cannot be undone.'),
t('Delete'),
t('Cancel')
);
return $form;
}
Notice I return a confirmation form first.
And here's the submit handler function that processes it after they submit the request:
function nates_module_form_delete_submit($form, &$form_state) {
global $user;
nates_module_entry_delete($form_state['values']['pid']);
drupal_set_message(t("Deleted entry"));
}
Then, edit your listing page to add the edit links and delete links:
function nates_module_list() {
$output = '';
// Get all entries in the dfp_amobee2 table.
if ($entries = nates_module_entry_load_all()) {
$rows = array();
foreach ($entries as $entry) {
// Sanitize the data before handing it off to the theme layer.
$entry->editlink = l('edit','admin/structure/nates-custom-page/update/' . $entry->pid, array('query' => array('destination' => 'admin/structure/nates-custom-page')));
$entry->deletelink = l('delete','admin/structure/nates-custom-page/delete/' . $entry->pid, array('query' => array('destination' => 'admin/structure/nates-custom-page')));
unset($entry->pid);
if(!empty($entry->tid)) {
$entry->alias = l($entry->alias, 'taxonomy/term/'.$entry->tid);
}
else if(isset($entry->pages)) {
if(drupal_valid_path($entry->pages)) {
$entry->alias = l(drupal_lookup_path('alias', $entry->pages),$entry->pages);
} else {
$entry->alias = check_markup($entry->pages);
}
} else {
$entry->alias = "";
}
unset($entry->pages);
if(!$entry->tid) {
$entry->tid = "";
}
$rows[] = (array) $entry;
}
// Make a table for them.
$header = array(t('path'), t('tid'), t('dfp tag machine_name'),t('amobee_as'), '', '');
$output .= '<p>' . t('If the "tid" is filled in, amobee_as will be used on taxonomy pages and on node pages (where the main term id matches). If the path is filled it, will be used on that path. Path supercedes "tid" when there is a conflict.') . '</p>';
$output .= theme('table', array('header' => $header, 'rows' => $rows));
}
else {
drupal_set_message(t('No entries have been added yet.'));
}
return $output;
}

Drupal 7 Rules custom action assign return data to a replacement pattern

How can I create a custom Rule-Action which will successfully save a value as a replacement pattern for use in the other actions?
I got some very good help here on retrieving Product-Display information from a Product-Order.
As I said, the linked answer helped a great deal but the returned path data for the Product-Display comes back in the http://www.mysite/node/77 format. However, I really just need the numeric value only so I can load the node by performing a Fetch entity by id action supplying the numeric value and publishing the Product-Display node etc.
So, I implemented a custom action which will take the Product-Display URL(node/77) and return 77.
I copied the Fetch entity by id code and modified it so my returned numeric value can be saved and used in other Actions. The code is below:
function my_custom_action_info(){
$actions['publish_product_display_node'] = array(
'label' => t('Fetch product-display id'),
'parameter' => array(
'type' => array(
'type' => 'uri',
'label' => t('My Action'),
'options list' => 'rules_entity_action_type_options2',
'description' => t('Specifies the product-display url.'),
),
),
'provides' => array(
'entity_fetched' => array('type' => 'integer', 'label' => t('Fetched entity')),
),
'group' => t('Entities'),
'access callback' => 'rules_entity_action_access',
);
return $actions;
}
function publish_product_display_node($path = null){
$parts = explode('node/', $path);
return $parts[1];
}
function rules_entity_action_type_options2($element, $name = NULL) {
// We allow calling this function with just the element name too. That way
// we ease manual re-use.
$name = is_object($element) ? $element->getElementName() : $element;
return ($name == 'entity_create') ? rules_entity_type_options2('create') : rules_entity_type_options2();
}
function rules_entity_type_options2($key = NULL) {
$info = entity_get_info();
$types = array();
foreach ($info as $type => $entity_info) {
if (empty($entity_info['configuration']) && empty($entity_info['exportable'])) {
if (!isset($key) || entity_type_supports($type, $key)) {
$types[$type] = $entity_info['label'];
}
}
}
return $types;
}
function rules_action_entity_createfetch_access2(RulesAbstractPlugin $element) {
$op = $element->getElementName() == 'entity_create' ? 'create' : 'view';
return entity_access($op, $element->settings['type']);
}
As I said I copied the modified code so I don't claim to thoroughly understand all the functions aside from publish_product_display_node.
My code modifications work as far as setting the Product-Display URL token as the argument and also setting an entity variable label(Display NID) and value(display_nid).
The problem is when I check display_nid in newly created actions, the value is empty.
I need help figuring out the how to successfully save my entity value so I can use it in following Actions.
in the function publish_product_display_node, can you verify that you don't need to be returning $parts[0], instead of $[parts[1]?
It's just that Drupal paths are frequently in the form 'node/7' or 'taxonomy/term/6', and if you explode with 'node/' as the separator, you'd only have a single value which would start at index 0 for nodes...
So, just wondering if that would solve your issue...

Can I create a Drupal autocomplete textfield in a block?

I want to create an auto-complete form in my custom module that will be loaded in a block. Drupal doesn't seem to be loading the necessary Javascript libraries to work properly. How do I know what needs to be loaded and how/where do I tell Drupal to load these libraries?
hook_block_view:
function my_module_block_view($delta = '') {
//The $delta parameter tells us which block is being reqested.
switch ($delta) {
case 'my_module_my_block':
$block['subject'] = t('Block Subject');
$block['content'] = drupal_get_form('my_module_my_form');
break;
}
return $block;
}
Form code:
function my_module_my_form($form, &$form_state) {
$form = array();
$form['term'] = array(
'#type' => 'textfield',
'#autocomplete_path' => 'my-module-autocomplete'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Add',
);
return $form;
}
The form loads, the field is there, but auto-complete isn't working :(
If I call the my-module-autocomplete path I do get a valid response back when compared with a Content Type edit form. The ajax spinner in the input field never appears so the ajax isn't being called. Realistically all I want is the autocomplete field...the submit will be handled manually.
It's probably because you're reseting $form to an empty array at the beginning of the function. In Drupal 7 there's a bunch of stuff added to that element before it's passed through to your form function (that's why $form is passed to your function whereas in Drupal 6 it wasn't).
Just remove $form = array(); and it should work, other than that your code looks perfect.
the following should work;
function mymodule_block_info() {
$blocks['mymodule'] = array(
// The name that will appear in the block list.
'info' => t('My Module'),
// Default setting.
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
function mymodule_block_view($delta = ''){
switch($delta){
case 'mymodule':
if(user_access('access content')){ //good idea to check user perms here
$block['subject'] = t('My Module');
$block['content'] = 'Hi :)';
$block['content'] = drupal_get_form('mymodule_form');
return $block;
}
break;
}
}
function mydmodule_menu() {
$items['module/autocomplete'] = array(
'page callback' => 'mymodule_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK
);
return $items;
}
function mymodule_form($form, &$form_state) {
$form['greenentry'] = array(
'#type' => 'textfield',
'#title' => t('Enter'),
'#autocomplete_path' => 'mymodule/autocomplete',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function mymodule_autocomplete($string) {
$matches = array();
// Some fantasy DB table which holds cities
$query = db_select('cities', 'c');
// Select rows that match the string
$return = $query
->fields('c', array('city'))
->condition('c.city', '%' . db_like($string) . '%', 'LIKE')
->range(0, 10)
->execute();
// add matches to $matches
foreach ($return as $row) {
$matches[$row->url] = check_plain($row->url);
}
// return for JS
drupal_json_output($matches);
}
this code is so pretty to add an auto-complete filed in block. But i just found a tiny notice here. if someone get an error
An ajax error occurred. http result code 200
then just add
exit();
after the line
drupal_json_output($matches);
hence fix the issue.

Themeless Page - Or a content-only content type

I need to create content that only outputs what I entered, no layout, no comments, blocks, etc.
If I could implement a custom content type that used blank templates that might work, but I've been unable to make it work so far as overriding the themes seems to replace everything site-wide. So, skipping that, is there a simple way I'm not aware of, to just output what I type in the content's body, with no layout/blocks/comments,etc.
Is it possible via a custom module to add a custom field at the bottom, and then during the process_page() hook, ignore the theming and layout and just output the content?
Please don't suggest "Views" as it's not stable.
Some example use cases:
A page that's a PHP type, and it's simply a script that I don't want layout as an example.
Or if I have some json data to return.
Or if I want to toss up a all-in-one page with it's own theme.
Any suggestions?
I am working on a module that will do this and also integrate with views so you can set a view to be "theme-less" as well. I have it so that it will create a checkbox on a node form that you can specify the node to be theme-less node. Once that is checked, the node will be displayed with no theme (the content only, no title).
It's a little hackish, but it works preliminarily. I will be fleshing this out as I have need for it and I will likely also integrate it with views over time.
timeless.install
<?php
/**
* themeless.install
* defines our schema for flagging nodes as being themeless or not.
*/
function themeless_schema() {
$schema['themeless_node'] = array(
'description' => 'Keeps track of which nodes are themeless.',
'fields' => array(
'nid' => array(
'description' => 'The node id of a themeless node',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary_key' => array('nid'),
);
return $schema;
}
function themeless_enable() {
if (db_table_exists('themeless_node') == FALSE) {
drupal_install_schema('themeless');
}
}
function themeless_uninstall() {
drupal_uninstall_schema('themeless');
}
timeless.module
function themeless_process(&$variables, $hook) {
if ($hook == 'page') {
if (isset($variables['page']['content']['system_main']['nodes']) && is_array($variables['page']['content']['system_main']['nodes'])) {
$node = $variables['page']['content']['system_main']['nodes'];
$nodes = array_keys($node);
$result = db_query("SELECT t.nid AS themeless, n.promote
FROM {themeless_node} t, {node} n
WHERE t.nid=:nid
AND n.nid=t.nid",
array('nid' => $nodes[0]));
$tdata = $result->fetchObject();
if (isset($tdata->themeless) && $tdata->themeless > 0 && $tdata->promote != 1) {
if ($node[$nodes[0]]['body']['#object']->body['und'][0]['format'] == 'php_code') {
print $node[$nodes[0]]['body'][0]['#markup'];
} else {
print $node[$nodes[0]]['body']['#object']->body['und'][0]['value'];
}
exit();
}
}
}
}
function themeless_form_alter(&$form, &$form_state, $form_id) {
$parts = explode('_',$form_id);
$form_type = $parts[count($parts)-1].'_'.$parts[count($parts)-2];
$themeless = '';
if ($form_type == 'form_node') {
if (isset($form_state['node']->nid) && $form_state['node']->nid) {
$themeless = db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $form_state['node']->nid))->fetchField();
}
$checked = ($themeless == 1) ? 'checked' : '';
$form['themeless'] = array(
'#type' => 'fieldset',
'#title' => t('Themeless Node'),
'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['themeless']['themeless_node'] = array(
'#type' => 'checkbox',
'#title' => 'Themeless Node',
'#description' => 'This theme will be displayed without any wrapper themes.',
'#weight' => 100,
'#default_value' => $themeless,
);
}
}
function themeless_node_insert($node) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
function themeless_node_update($node) {
if ($node->themeless_node == 1) {
if (db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $node->nid))->fetchField() != 1) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
} else {
$result = db_query("DELETE FROM {themeless_node}
WHERE nid=:nid",array('nid' => $node->nid));
}
}
timeless.info
name = Themeless
description = Gives the option to a node to have a themeless display or displayed without the various theme templates native to Drupal.
core = 7.x
version = 7.x-1.0dev

Resources