How to create drupal Batch Operation on Custom Form - drupal-7

I am learing batch operations api. i have tried to create a batch operation using a form here is my hook_form
function batch_form_get_form($form, &$form_state){
$form = array();
$form['select'] = array(
'#title' => 'Select',
'#type' =>'select',
'#options' => array(
'batch1' => 'Batch 1',
'batch2' => 'Batch 2',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit'
);
return $form;
}
here is my form submit function
function batch_form_get_form_submit($form,&$form_state){
$function = 'batch_process_form';
$_SESSION['http_request_count'] =0;
$batch = $function;
batch_set($batch);
dsm ($function);
}
here is my batch process function which i used on batch_set function
function batch_process_form(){
for($i=0; $i<10; $i++){
$operations[] = array('batch_operation_result',array($i));
}
$title = "Batch Started";
$init_message = "Initialing Batch";
$progress_message = "Work in Progress";
$batch = array(
'operations' => $operations,
'title' => $title,
'init_message' => $init_message,
'progress_message' => $progress_message,
);
return $batch;
}
when i tried to run the batch i got the following error
Fatal error: Unsupported operand types in /home/dina/static/d7/includes/form.inc on line 4396
on the line no 4396 of form.inc
$batch_set = $init + $batch_definition + $defaults;
i don't no what i am missing

I think you missed one thing.
In your submit function, instead of
$batch = $function;
try
$batch = $function();
Good luck

Related

Drupal form api file upload with auto compression

I have written a module with form api which can upload image with dynamic file name. I want to upload that file with auto compression. I cannot understand how will I achieve this. How can I implement this in submit callback.
Below my code:
function MYMODULE_registration_form() {
$form['name'] = array(
'#title'=> t('Name'),
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 40,
'#attributes' => array('placeholder' => t('Enter your name'),),
);
$form['personal_info']['upload_pic'] = array(
'#title' => t('Upload Photo'),
'#type' => 'file',
'#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif, bmp'),
);
$form['submit'] = array(
'#value' => t('Submit'),
'#type' => 'submit',
);
$form['#attributes']['enctype'] = 'multipart/form-data';
return $form;
}
function MYMODULE_registration_form_submit($form, $form_state) {
$name = $form_state['values']['name'];
$count = 1;
$original_username = $name;
while (user_load_by_name($name)) {
$name = $original_username . $count++;
}
$validators = array(
'file_validate_extensions' => array('png gif jpg jpeg bmp')
);
$uploadCheck = file_save_upload('upload_pic', $validators);
if($uploadCheck) {
$parts = pathinfo($uploadCheck->filename);
$imagename = str_replace(' ', '_',$original_username.'_'. $count . '.'. $parts['extension']);
$target = "public://attorneys/".$imagename;
file_move($uploadCheck, $target, FILE_EXISTS_REPLACE);
$picture_fid = $uploadCheck->fid;
}
}
After a lot of R&D I have come to this conclusion and it is working fine:
Implement gulp package and install image optimisation plugin.
Take ref from this url : https://www.tutorialspoint.com/gulp/gulp_optimizing_images.htm

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 form theme function not being called

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;
}

Drupal 7: File field causes error with Dependable Dropdowns

I'm building a Form in a module using the Form API. I've had a couple of dependent dropdowns that have been working just fine. The code is as follows:
$types = db_query('SELECT * FROM {touchpoints_metric_types}') -> fetchAllKeyed(0, 1);
$types = array('0' => '- Select -') + $types;
$selectedType = isset($form_state['values']['metrictype']) ? $form_state['values']['metrictype'] : 0;
$methods = _get_methods($selectedType);
$selectedMethod = isset($form_state['values']['measurementmethod']) ? $form_state['values']['measurementmethod'] : 0;
$form['metrictype'] = array(
'#type' => 'select',
'#title' => t('Metric Type'),
'#options' => $types,
'#default_value' => $selectedType,
'#ajax' => array(
'event' => 'change',
'wrapper' => 'method-wrapper',
'callback' => 'touchpoints_method_callback'
)
);
$form['measurementmethod'] = array(
'#type' => 'select',
'#title' => t('Measurement Method'),
'#prefix' => '<div id="method-wrapper">',
'#suffix' => '</div>',
'#options' => $methods,
'#default_value' => $selectedMethod,
);
Here are the _get_methods and touchpoints_method_callback functions:
function _get_methods($selected) {
if ($selected) {
$methods = db_query("SELECT * FROM {touchpoints_m_methods} WHERE mt_id=$selected") -> fetchAllKeyed(0, 2);
} else {
$methods = array();
}
$methods = array('0' => "- Select -") + $methods;
return $methods;
}
function touchpoints_method_callback($form, &$form_state) {
return $form['measurementmethod'];
}
This all worked fine until I added a file field to the form. Here is the code I used for that:
$form['metricfile'] = array(
'#type' => 'file',
'#title' => 'Attach a File',
);
Now that the file is added if I change the first dropdown it hangs with the 'Please wait' message next to it without ever loading the contents of the second dropdown. I also get the following error in my JavaScript console:
"Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'handleError'"
What am I doing wrong here?

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!

Resources