drupal 7 form theme function not being called - drupal-7

I'm trying to register a theme function for a simple form in a custom module, but the theme function is not being called. I just get the basic form.
Here's my hook_theme():
function kss_membership_theme($existing, $type, $theme, $path){
$items = array();
$items['kss_membership_payment_form'] = array(
'render element' => 'form',
);
return $items;
}
for this form:
/**
* Returns the form for the second page of the payment process
*/
function kss_membership_payment_form($form, &$form_state) {
$form['description'] = array(
'#type' => 'item',
'#title' => t('We currently accept Paypal payments'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#submit' => array('kss_membership_payment_form_submit'),
);
$form['#theme'] = array('theme_kss_membership_payment_form');
return $form;
}
and here is the theme function:
function theme_kss_membership_payment_form($variables) {
// Isolate the form definition form the $variables array
$form = $variables['form'];
$output = '<h2>' . t('Please enter your information below') . '</h2>';
$output .= '<div id="personal_details">';
$output .= drupal_render($form['description']);
$output .= drupal_render($form['submit']);
// Additional template output goes here....
$output .= '</div>';
$output .= drupal_render_children($form);
return $output;
}

You are very near to solution, Only one problem is there.
theme calling is wrong
$form['#theme'] = array('theme_kss_membership_payment_form');
you are required to call
$form['#theme'] = array('kss_membership_payment_form');
After that You must required to clear the cache from the admin => configuration => Performance => Clear Cache button.
/**
* Returns the form for the second page of the payment process
*/
function kss_membership_payment_form($form, &$form_state) {
$form['description'] = array(
'#type' => 'item',
'#title' => t('We currently accept Paypal payments'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#submit' => array('kss_membership_payment_form_submit'),
);
$form['#theme'] = array('kss_membership_payment_form');
return $form;
}

Related

How to pass dynamic file location in Form API?

my requirement is to upload files to specific folders. How can I achieve this by using form api.
How can I modify below code such that upload_location should be dynamic. Uploaded file should save into the Folder name provided by the user.
#submit element is not calling custom_document_submit function.
$form['folder_name'] = array(
'#type' => 'textfield',
'#title' => t('Folder Name'),
);
$form['document'] = array(
'#type' => 'managed_file',
'#upload_validators' => array('file_validate_extensions' => array('xml')),
'#upload_location' => 'public://',
'#submit' => array('custom_document_submit'),
);
function custom_document_submit($form, &$form_state){
$destination = $form_state['values']['folder_name'];
$validators = array();
$file = file_save_upload('document', $validators, 'public://'.$destination);
}
The #submit property cannot be declare on a managed_file form object...
Instead, you have to add or to modify a submit action on your form (or button).
$form['#submit'][] = 'custom_document_submit';
If you don't want to modify the submit method of your form, you can also simply add a validator (with the #validate property), witch will modify the '#upload_location' property of your document depending on the folder_name value.
Both, #submit and #validate properties have to be added to the form itself.
<?php
define('IMPORT_DIRECTORY_PATH', 'public://import');
$form['folder_name'] = array(
'#type' => 'textfield',
'#title' => t('Folder Name'),
);
form['document'] = array(
'#title' => t('Upload .xml'),
'#type' => 'managed_file',
'#upload_validators' => array(
'file_validate_extensions' => array('xml'),
),
'#process' => array('import_document_element_process'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Upload'),
'#submit' => array('custom_document_submit'),
);
function custom_document_submit($form, &$form_state){
// Validate extensions.
$validators = array(
'file_validate_extensions' => array('xml'),
);
$file = file_save_upload('document', $validators, FALSE, FILE_EXISTS_RENAME);
// If the file passed validation.
if ($file) {
// Rename uploaded file to prevent cache from remembering name file.
$directory = SCHEDULES_IMPORT_DIRECTORY_PATH;
if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
$uri = $directory . '/xml_' . $file->uid . '_' . $file->timestamp . '.xml';
if ($file = file_move($file, $uri)) {
$form_state['values']['document'] = $file;
}
else {
form_set_error('document', t('The file could not be uploaded.'));
}
}
else {
form_set_error('document', t('The directory is not writable.'));
}
}
else {
form_set_error('document', t('The file extension is not correct.'));
}
// dpm($form_state['values']['document']);
// var_dump( $form_state['values']['document']);
}
/**
* Removing the upload button in managed files.
*/
function import_document_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#access'] = FALSE;
return $element;
}

Drupal 7 custom form module

My form using custom module is not appearing on my contact us page.I created my .module file and .info file and then active the module as well. Following is the code I had included in my .module file
function custom_form_module_form($form,&$form_state) {
$form['name'] = array(
'#type' => 'textfield',
);
$form['company'] = array(
'#type' => 'textfield',
);
$form['phone'] = array(
'#type' => 'textfield',
);
$form['email'] = array(
'#type' => 'textfield',
);
$form['message'] = array(
'#type' => 'textfield',
);
return $form;
}
and in my template.php file
function custom_form_module_form_theme($existing, $type, $theme, $path) {
$items['custom_form_module_form'] = array(
'render element' => 'form',
'template' => 'page--contact-us',
'path' => drupal_get_path('theme', 'escorts').'/templates');
return $items;
}
and in my page--contact-us.tpl.php I used the following line to call separate fields of a form but its not working.
<?php echo drupal_render($form['name']); ?>
"here custom_form_module=my module name and page--contact-us.tpl.php=my template file and escorts=my theme name"
To print the form in the contact page, you may not use template.php.
Simply:
$my_form = drupal_get_form('custom_form_module_form');
print drupal_render($my_form);
Update
Change the form markup from from your template.php
function theme_my_form_1($form) {
$vars['element'] = $form;
$markup = '';
$markup .= '<div id="form-name-wrapper">'
. drupal_render($form['name'])
. '</div>';
// continue altering the markup
$vars['element']['#children'] = $output;
return theme_form($vars);
}
Then, in your .tpl.php file:
$my_form = drupal_get_form('custom_form_module_form');
print theme_my_form_1($my_form);

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.

How does a form call itself on submit in Drupal

I am creating a custom module that I would like to use to display a form, from a module. The form queries a database and displays some information. The database connection is working, and the data has been retrieved successfully. The form has also been displayed successfully, but what I can figure out is how to link all together to have the page displayed again when submitting the form. My code is:
<?php
function menu($may_cache) {
$items = array();
$items['admin/reporting/report_details'] = array(
'title' => 'Report: User details by stores',
'access arguments' => array('access content'),
'page callback' => 'say_report_details',
'type' => MENU_CALLBACK,
);
return $items;
}
// This function should execute the logic if the $_GET variable is set
function say_report_details($values = array()) {
// The $_GET logic will be somtehing like this
// if (count($_GET) > 0)
// Get all the form values from the $_GET wit something like:
// if (count($_GET) > 0) {
// $start = mktime(0, 0, 0, $_GET['from_month'], $_GET['from_day'],
$_GET['from_year']);
// $end = mktime(23, 59, 59, $_GET['to_month'], $_GET['to_day'], $_GET['to_year']);
if ($_GET['store'] > 0) {
$form = drupal_get_form("report_details_form");
$output = theme("report_page", $form, $output);
return $output;
}
function report_details_form() {
$form["search"] = array(
'#type' => 'fieldset',
'#title' => t('Search params'),
'#collapsible' => FALSE,
'#tree' => TRUE,
);
for ($i = 1; $i < 32; $i++) {
$days_opt[$i] = $i;
}
for ($i = 1; $i < 13; $i++) {
$month_opt[$i] = $i;
}
for ($i = 2008; $i < date("Y") + 3; $i++) {
$year_opt[$i] = $i;
}
$form["search"]["from_day"] = array(
'#type' => 'select',
'#title' => 'Date from',
'#options' => $days_opt,
'#default_value' => (($_GET['from_day'] == "") ? date("d") : $_GET['from_day'])
);
$form["search"]["from_month"] = array(
'#type' => 'select',
'#title' => ' ',
'#options' => $month_opt,
'#default_value' => (($_GET['from_month'] == "") ? date("m") : $_GET['from_month'])
);
$form["search"]["from_year"] = array(
'#type' => 'select',
'#title' => ' ',
'#options' => $year_opt,
'#default_value' => (($_GET['from_year'] == "") ? date("Y") : $_GET['from_year'])
);
$form["search"]["to_day"] = array(
'#type' => 'select',
'#title' => 'Date to',
'#options' => $days_opt,
'#default_value' => (($_GET['to_day'] == "") ? date("d") : $_GET['to_day'])
);
$form["search"]["to_month"] = array(
'#type' => 'select',
'#title' => ' ',
'#options' => $month_opt,
'#default_value' => (($_GET['to_month'] == "") ? date("m") : $_GET['to_month'])
);
$form["search"]["to_year"] = array(
'#type' => 'select',
'#title' => ' ',
'#options' => $year_opt,
'#default_value' => (($_GET['to_year'] == "") ? date("Y") : $_GET['to_year'])
);
$result = db_query('SELECT taxonomy_term_data.name, taxonomy_term_data.tid FROM
taxonomy_term_data WHERE vid = 10');
$strs = array("all" => "All");
foreach ($result as $store) {
$strs[$store->tid] = $store->name;
}
$form["search"]["store"] = array(
'#type' => 'select',
'#title' => 'Stores',
'#options' => $strs,
'#default_value' => $_GET['store']
);
$form["submit"] = array("#type" => "submit", "#value" => "Show report");
return $form;
}
function theme_report_page($form, $result = array()) {
$output = '
<div id="report_form">
'. $form .'
</div>
<div id="report_result">
'. $result .'
</div>
';
return $output;
}
function theme_report_details_form($form) {
unset($form['search']['from_day']['#title']);
unset($form['search']['from_month']['#title']);
unset($form['search']['from_year']['#title']);
unset($form['search']['to_day']['#title']);
unset($form['search']['to_month']['#title']);
unset($form['search']['to_year']['#title']);
unset($form['search']['store']['#title']);
$output = "<fieldset>
<legend>Search params</legend>
<div class='fieldtitles'>". t('Date From') .":</div>
". drupal_render($form['search']['from_day']) ."
". drupal_render($form['search']['from_month']) ."
". drupal_render($form['search']['from_year']) ."
<div class='clearing'> </div>
<div class='fieldtitles'>". t('Date To') .":</div>
". drupal_render($form['search']['to_day']) ."
". drupal_render($form['search']['to_month']) ."
". drupal_render($form['search']['to_year']) ."
<div class='clearing'> </div>
<div class='fieldtitles'>". t('Store') .":</div>
". drupal_render($form['search']['store']) ."
<div class='clearing'> </div>
". drupal_render($form['submit']) ."
</fieldset>";
unset($form['search']);
$output .= drupal_render($form);
return $output;
}
function report_details_form_submit($form_id, $form_values) {
$query = "";
// This next line is the one we are having an issue right now, as is trowing an
error due to $form_values is empty for some UNKNOWN reason...
foreach ($form_values['search'] as $key => $value) {
$query .= "&". $key ."=". $value;
}
return array('admin/reporting/report_details', $query);
}
I did not look over all the details of the form, but the submit function for D7 should look like this:
function my_module_example_form_submit($form, &$form_state) {
// do something
}
I think that should fix the problem. If not check out this link: http://api.drupal.org/api/drupal/includes%21form.inc/group/form_api/7
Please read & follow the answer mikewink provided.
In addition in the three working forms that I've created the menu item array is as follows:
$items = array();
$items['admin/config/system/dataforms/SiteAccessform']=array(
'title'=>'Site Access' //this should be watever the Title of your form is
,'description'=>'Configuration for the Data Forms module' //shows up by your menu item as it's description (where applicable)
,'page callback'=>'drupal_get_form' //this, as I understand it, is required for forms to work properly (& may be part of the cause of your problems)
,'page arguments'=>array('dataforms_main_form') //IMPORTANT this is the actual name of your function that will be executed to produce the form
,'access arguments'=>array('administer settings for dataforms') //??
,'type'=>MENU_CALLBACK//these work when the path is accessed though no menu items are created
,
);
A few more points, when you are on a particular 'menu' item with it's page arguments array element set to your form, it considers it ONE form only. That is to say that the one function will be the only function that will be able to create a form (in my experience). Therefore use logic in that function to produce different forms if applicable... ,(as opposed to attempting to have a button that calls another function... which did not work for me).
Also, again referring back to mikewink's answer, the $form_state variable is the method of storing state that you want to pay attention, & not the standard $_GET or $_POST variables.
This link might be mildly helpful: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7
However I gleaned the most valuable information from the examples module: https://drupal.org/project/examples
Good Luck!

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.

Resources