I'm currently stuck on a problem I can't figure out on a wordpress side project. Here's the thing :
I made a plugin that queries an API, and processes its data to insert posts.
The problem I face is that, when the main function is triggered manually (i.e. via a route or cron manually launched) posts are correctly created or updated, but when the cron executed automatically, posts are always duplicated. I may have narrowed the problem down to capabilities (I check if posts exists by querying the cpt for a unique meta-field), and when the cron executes on its own, it find no ids.
Here are code samples :
public function insertPosts() {
set_current_user(1); // <- here I tried setting the user as admin for the script, but it didn't work
// First, get all prestations from the api
$prestations = $this->api->getPrestations();
/*
* Then :
* we remove sessions of formations initiales, which are useless (gamme id 10 = formations initiales)
* I could have "only" taken the ids I need, but unsetting useless array entries allows for a lighter dataset
*/
$prestations_info = [];
foreach ($prestations as $key => $prestation) {
if ($prestation['gamme']['id'] == 10) {
// Removes the useless $prestation and breaks out of the loop so its ID's not stored
unset($prestations[$key]);
continue;
}
$prestations_info[] = [
'fid' => $prestation['id'],
'cat_name' => $prestation['gamme']['name'],
'cat_id' => $prestation['gamme']['id']
];
}
/*
* Then :
* Parse the array to process every id individually and query the api for core informations for the singles
*/
foreach ($prestations_info as $presta) {
// Meta query to check if a post with the formation's id already exists
$args = [
'post_type' => 'formations',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'api_fid',
'value' => $presta['fid'],
'compare' => '='
]
]
];
$posts = new WP_Query($args);
if ($posts->have_posts()) {
while ($posts->have_posts()) {
// If a post with that formation id already exists, we retrieve its ID:
// this way, we can update existing post and avoid duplicates
$posts->the_post();
$post_id = get_the_ID();
}
}
$body = $this->api->getSessionsByPrestationsId($presta['fid']);
$post_array = [];
$locations = [];
$nb_places = [];
foreach ($body as $key => $item) {
if (!empty($item['seances'])) {
$duration = BOUtilities::getFormationDuration($item['seances']);
$dates = BOUtilities::getDatesPerSessions($item['seances']);
}
if ($dates) {
$session_date = [];
if (is_array($dates)) {
foreach ($dates as $i => $date) {
$session_date[$i] = [
'dates' => $date['start'] .' - ' . $date['end'],
];
}
} else {
$session_date[] = [
'dates' => $dates,
];
}
}
if (!empty($item['location'])) {
$locations[] = strtolower($item['location']);
$session[] = [
'sessions_location' => $item['location'],
'sessions_dates' => $session_date,
];
}
if (!empty($item['nbplace']) && $item['nbplace'] != 0) {
if (!in_array($item['nbplace'], $nb_places)) {
$nb_places[] = $item['nbplace'];
}
}
if ($item['price'] != 0) {
$prices[] = $item['price'];
}
}
$formatted_cost = BOUtilities::setPrices($prices);
$effectifs = BOUtilities::setEffectifs($nb_places);
if ($post_id) {
$post_array = [
'ID' => $post_id,
'post_type' => 'formations',
'post_title' => $item['prestation']['name'],
'meta_input' => [
'api_fid' => $presta['fid'],
'aside_cost' => $formatted_cost,
'aside_duration' => ($duration > 1 ? $duration . ' jours' : $duration . ' jour'),
'aside_effectifs' => $effectifs,
]
];
$inserted_post = wp_update_post($post_array);
}
else {
$post_array = [
'post_type' => 'formations',
'post_title' => $item['prestation']['name'],
'meta_input' => [
'api_fid' => $presta['fid'],
'aside_cost' => $formatted_cost,
'aside_duration' => ($duration > 1 ? $duration . ' jours' : $duration . ' jour'),
'aside_effectifs' => $effectifs,
]
];
$inserted_post = wp_insert_post($post_array);
}
// The cron does not have the capability of adding taxonomy terms, they need to be be added separately
$inserted_terms = wp_set_object_terms($inserted_post, $presta['cat_name'], 'categories_formations');
$inserted_terms = wp_set_object_terms($inserted_post, $locations, 'ville');
update_field('aside_sessions', $session, $inserted_post);
unset($dates);
unset($session);
unset($formatted_cost);
unset($nb_places);
unset($prices);
}
}
This is very much work in progress, but, for now, I am stumped.
Related
Assuming I have a CSV like this:
value1,value2
value1,value2
and a table with two columns
column1|column2
how can I programatically import the CSV into the table?
#erier's answer is really good and will get the job done.
As the question is tagged with Drupal 7 I thought I would submit a Drupal custom module method, adapting #erier's answer and prettifying it.
For the basics of a custom module, you can see this simple example.
function custom_module_form($form, &$form_state) {
$form['csv_upload'] = array(
'#type' => 'file',
'#title' => t('Choose a file'),
'#title_display' => 'invisible',
'#size' => 22,
'#upload_validators' => array('file_clean_name' => array()),
);
$form['upload'] = array(
'#type' => 'submit',
'#value' => 'Upload',
);
}
function custom_module_form_validate($form, &$form_state) {
$validators = array('file_validate_extensions' => array('csv'));
// Check for a new uploaded file.
$file = file_save_upload('csv_upload', $validators);
//$file = $form_state['values']['csv_upload'];
if (isset($file)) {
// File upload was attempted.
if ($file) {
// Put the temporary file in form_values so we can save it on submit.
$form_state['values']['csv_upload_file'] = $file;
}
else {
// File upload failed.
form_set_error('csv_upload', t('The file could not be uploaded.'));
}
}
}
function custom_module_submit($form, &$form_state) {
$file = $form_state['values']['csv_upload_file'];
$file->status = FILE_STATUS_PERMANENT;
$file->filename = str_replace(' ', '_', $file->filename);
file_save($file);
$csv_file = file_load($file->fid);
$file = fopen($csv_file->uri, "r");
while(! feof($file))
{
$customer = fgetcsv($file));
db_insert('your_db_table')
->fields(array(
'column1' => $customer[0],
'column2' => $customer[1]
))
->execute();
}
fclose($file);
drupal_set_message('CSV data added to the database');
}
function file_clean_name($file) {
$file->filename = str_replace(' ', '_', $file->filename);
}
That is assuming your question was about a database table.
If you meant into an html table, you can adapt the submit function after $csv_file = file_load($file->fid); like this:
$headers = array('column 1', 'column 2');
$rows = array();
$file = fopen("contacts.csv","r");
while(! feof($file))
{
$customer = fgetcsv($file));
$rows[] = array($customer[0], $customer[1]);
}
fclose($file);
return theme('table', array('header' => $headers, 'rows' => $rows);
Or adapt the two by adding the data to the database and displaying to the screen without a second database hit.
This is what I've come up with - I'm no PHP expert - and it doesn't seem pretty - but it works!
$handle = fopen('/path/to/file/filename.csv', 'r');
$row = fgetcsv($handle);
for ($e = 0; $row = fgetcsv($handle); $e++) {
$record = array();
foreach ($row as $field) {
$record[] = $field;
}
db_insert('your_db_table')
->fields(array(
'column1' => $record[0],
'column2' => $record[1]
))
->execute();
}
fclose($handle);
The table will then look like this:
column1|column2
---------------
value1|value2
value1|value2
This module may help you
https://www.drupal.org/sandbox/draenen/2442165
It requires Feeds but it extends it to work with custom tables (non drupal entities)
I am trying to modify a plugin. I need the author id of the current post to accomplish what I am doing. I have tried every other method I have found over internet that claims to get the post author id outside the loop but its not working inside the plugin. I guess its because the plugins might be loaded before the loop variables or something? Please pardon me as I am not a Pro.
Here is what I have tried so far.
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
But nothing works in the plugin's directory. Can anyone help?
Detailed Explanation:
I am trying to modify woodiscuz plugin. The problem with this plugin is that it held comments of even seller for moderation. So if I am the seller and I reply to some buyer in comment, I will have to approve my own comment.
Now to overcome this problem, I am putting a condition that if the author of the post (seller) is commenting, then don't put the comment for moderation.
Here is the function of the plugin that is controlling comments.
public function comment_submit_via_ajax() {
$message_array = array();
$comment_post_ID = intval(filter_input(INPUT_POST, 'comment_post_ID'));
$comment_parent = intval(filter_input(INPUT_POST, 'comment_parent'));
if (!$this->wpc_options->wpc_options_serialized->wpc_captcha_show_hide) {
if (!is_user_logged_in()) {
$sess_captcha = $_SESSION['wpc_captcha'][$comment_post_ID . '-' . $comment_parent];
$captcha = filter_input(INPUT_POST, 'captcha');
if (md5(strtolower($captcha)) !== $sess_captcha) {
$message_array['code'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_captcha'];
echo json_encode($message_array);
exit;
}
}
}
$comment = filter_input(INPUT_POST, 'comment');
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$user = get_userdata($user_id);
$name = $user->display_name;
$email = $user->user_email;
$user_url = $user->user_url;
} else {
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
$user_id = 0;
$user_url = '';
}
$comment = wp_kses($comment, array(
'br' => array(),
'a' => array('href' => array(), 'title' => array()),
'i' => array(),
'b' => array(),
'u' => array(),
'strong' => array(),
'p' => array(),
'img' => array('src' => array(), 'width' => array(), 'height' => array(), 'alt' => array())
));
$comment = $this->wpc_helper->make_clickable($comment);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && $comment && filter_var($comment_post_ID)) {
$held_moderate = 1;
if ($this->wpc_options->wpc_options_serialized->wpc_held_comment_to_moderate) {
$held_moderate = 0;
}
// $held_moderate = 1 -> No moderation
/*This is the part where I need to put the custom condition*/
if($post_author_id == get_current_user_id())
{
$held_moderate = 1;
}
$new_commentdata = array(
'user_id' => $user_id,
'comment_post_ID' => $comment_post_ID,
'comment_parent' => $comment_parent,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_author_url' => $user_url,
'comment_type' => 'woodiscuz',
'comment_approved' => $held_moderate
);
$new_comment_id = wp_insert_comment($new_commentdata);
$new_comment = new WPC_Comment(get_comment($new_comment_id, OBJECT));
if (!$held_moderate) {
$message_array['code'] = -2;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_held_for_moderate'];
} else {
$message_array['code'] = 1;
$message_array['message'] = $this->comment_tpl_builder->get_comment_template($new_comment);
}
$message_array['wpc_new_comment_id'] = $new_comment_id;
} else {
$message_array['code'] = -1;
$message_array['wpc_new_comment_id'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_field'];
}
echo json_encode($message_array);
exit;
}
I'm trying to get only my second level categories from a 3 depth category structure in woocommerce.
But it always returns the 3rd level aswell.
/**
* Get second level cat
*/
function get_second_cat_level($parent_id) {
$subcats = array();
$args = array(
'parent' => $parent_id,
'taxonomy' => 'product_cat',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'hide_empty' => 0
);
$cats = get_categories($args);
foreach ($cats as $cat) {
$subcats[] = $cat;
var_dump($cat);
}
return $cats;
}
I assume that $parent_id is the string id of the parent_category.
This is just crazy.
As no one seems to have any solution for me, I will share one solution I used. But be carefull, this is very specific to 3 depth level category groups.
I created 2 functions :
one to get the category object from the id, the slug or the name of the given category :
function get_product_category($field, $value) {
$authorized_fields = array(
'term_id',
'name',
'slug'
);
// Check if field and value are set and not empty
if (!isset($field) || empty($field) || !isset($value) || empty($value)) {
$response = "Error : check your args, some are not set or are empty.";
}
else {
// Check if the specified field is part of the authorised ones
if (!in_array($field, $authorized_fields)) {
$response = "Unauthorised field $field"; }
else {
// init exists var to determine later if specified value matches
$exists = false;
$product_cats = get_terms('product_cat', array(
'hide_empty' => 0,
'orderby' => 'name'
));
// the loop will stop once it will have found the matching value in categories
foreach ($product_cats as $product_cat) {
if($product_cat->$field == $value) {
$response = $product_cat;
$exists = true;
break;
}
}
if ($exists == false) {
$response = array(
"message" => "Error with specified args",
"field" => "$field",
"value" => "$value"
);
}
}
}
return $response;
}
The second function uses the first one to return the 2nd level categories. It uses an argument $dep which, when is tested alone as false, returns another result which I needed somewhere else. So don't pay attention to it.
function get_first_child_cat_only ($cat_id, $dep = true) {
// Array which handle all the 2nd child sub cats
$subcats = array();
// $cat_id is the parent (1st level) cat id
$categories = get_term_children( $cat_id, 'product_cat' );
foreach ($categories as $sub_category) {
if ($dep == true && get_term_children( $sub_category, 'product_cat' )) {
$subcats[] = get_product_category('term_id', $sub_category);
}
elseif($dep == false) {
$subcats[] = get_product_category('term_id', $sub_category);
}
}
return $subcats;
}
Little explanation : the above function return only sub catégories which has categories children. So it ignores the last (3rd one) which have no children and returns the second one only.
This can certainly be improved, and I know I'll probably get some "criticisms" and actually, I hope so ! So don't hesitate :)
I'm trying to setup a batch page for processing and I need an example. The example that's given in the Example module is within a form and I need a page that I can run independently of a form that will process batch requests.
For instance:
function mymodule_batch_2() {
$operations[] = array('mymodule_onefunction','mymodule_anotherfunction')
$batch = array(
'operations' => $operations,
'finished' => 'mymodule_finished',
// We can define custom messages instead of the default ones.
'title' => t('Processing batch 2'),
'init_message' => t('Batch 2 is starting.'),
'progress_message' => t('Processed #current out of #total.'),
'error_message' => t('Batch 2 has encountered an error.'),
);
batch_set($batch);
batch_process('');
}
Where the batch function would call other functions in the form of $operations.
You need to give batch process an id to work from. batch_process('mybatch')otherwise yourmexample is correct. are you having a particular problem with this strategy?
Here you can see my sample of batch relization with form that calls batch:
function my_module_menu() {
$items['admin/commerce/import'] = array(
'title' => t('Import'),
'page callback' => 'drupal_get_form',
'page arguments' => array('my_module_settings_form'),
'access arguments' => array('administer site settings'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Import form
*/
function my_module_settings_form() {
$form = array();
$form['import'] = array(
'#type' => 'fieldset',
'#title' => t('Import'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['import']['submit'] = array(
'#type' => 'submit',
'#value' => t('Import'),
);
return $form;
}
function my_module_settings_form_submit($form, &$form_state) {
batch_my_module_import_start();
}
/**
* Batch start function
*/
function batch_my_module_import_start() {
$batch = array(
'title' => t('Import products'),
'operations' => array(
array('_batch_my_module_import', array()),
),
'progress_message' => t('Import. Operation #current out of #total.'),
'error_message' => t('Error!'),
'finished' => 'my_module_batch_finished',
);
batch_set($batch);
}
/**
* Import from 1C operation. Deletes Products
*/
function _batch_my_module_import(&$context) {
// Your iterms. In my case select all products
$pids = db_select('commerce_product', 'p')
->fields('p', array('sku', 'product_id', 'title'))
->condition('p.type', 'product')
->execute()
->fetchAll();
// Get Count of products
if (empty($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['max'] = count($pids);
watchdog('import', 'import products');
}
// Create Iteration variable
if (empty($context['sandbox']['iteration'])) {
$context['sandbox']['iteration'] = 0;
}
// Check for the end of cycle
if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {
// Count of operation in one batch step
$limit = 10;
// Counts completed operations in one batch step
$counter = 0;
if ($context['sandbox']['progress'] != 0) {
$context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
}
// Loop all Product items in xml
for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {
/* Loop items here */
/* ... */
/* ... */
$context['results']['added']['products'][] = $product_item->title;
// Update Progress
$context['sandbox']['progress']++;
$counter++;
// Messages
$context['message'] = t('Now processing product %name. Product %progress of %count', array('%name' => $product_item->title, '%progress' => $context['sandbox']['progress'], '%count' => $context['sandbox']['max']));
$context['results']['processed'] = $context['sandbox']['progress'];
}
}
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
/**
* Finish of batch. Messagess
*/
function my_module_batch_finished($success, $results, $operations) {
if ($success) {
drupal_set_message(t('#count products added.', array('#count' => isset($results['added']) ? count($results['added']) : 0)));
}
else {
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing #operation with arguments : #args', array('#operation' => $error_operation[0], '#args' => print_r($error_operation[0], TRUE))));
}
watchdog('import', 'import finished');
}
function module_name_import_form_submit($form, $form_state) {
// Check to make sure that the file was uploaded to the server properly
$uri = db_query("SELECT uri FROM {file_managed} WHERE fid = :fid", array(
':fid' => $form_state['input']['import']['fid'],
))->fetchField();
if(!empty($uri)) {
if(file_exists(drupal_realpath($uri))) {
// Open the csv
$handle = fopen(drupal_realpath($uri), "r");
// Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
// If you want commas are any other character, replace the pipe with it.
while (($data = fgetcsv($handle, 0, '|', '"')) !== FALSE) {
$operations[] = array(
'module_name_import_batch_processing', // The function to run on each row
array($data), // The row in the csv
);
}
// Once everything is gathered and ready to be processed... well... process it!
$batch = array(
'title' => t('Importing CSV...'),
'operations' => $operations, // Runs all of the queued processes from the while loop above.
'finished' => 'module_name_import_finished', // Function to run when the import is successful
'error_message' => t('The installation has encountered an error.'),
'progress_message' => t('Imported #current of #total products.'),
);
batch_set($batch);
fclose($handle);
}
}
else {
drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
}
}
/**
* This function runs the batch processing and creates nodes with then given information
* #see
* module_name_import_form_submit()
*/
function module_name_import_batch_processing($data) {
// Lets make the variables more readable.
$title = $data[0];
$body = $data[1];
$serial_num = $data[2];
// Find out if the node already exists by looking up its serial number. Each serial number should be unique. You can use whatever you want.
$nid = db_query("SELECT DISTINCT n.nid FROM {node} n " .
"INNER JOIN {field_data_field_serial_number} s ON s.revision_id = n.vid AND s.entity_id = n.nid " .
"WHERE field_serial_number_value = :serial", array(
':serial' => $serial_num,
))->fetchField();
if(!empty($nid)) {
// The node exists! Load it.
$node = node_load($nid);
// Change the values. No need to update the serial number though.
$node->title = $title;
$node->body['und'][0]['value'] = $body;
$node->body['und'][0]['safe_value'] = check_plain($body);
node_save($node);
}
else {
// The node does not exist! Create it.
global $user;
$node = new StdClass();
$node->type = 'page'; // Choose your type
$node->status = 1; // Sets to published automatically, 0 will be unpublished
$node->title = $title;
$node->uid = $user->uid;
$node->body['und'][0]['value'] = $body;
$node->body['und'][0]['safe_value'] = check_plain($body);
$node->language = 'und';
$node->field_serial_number['und'][0]['value'] = $serial_num;
$node->field_serial_number['und'][0]['safe_value'] = check_plain($serial_num);
node_save($node);
}
}
/**
* This function runs when the batch processing is complete
*
* #see
* module_name_import_form_submit()
*/
function module_name_import_finished() {
drupal_set_message(t('Import Completed Successfully'));
}
I am adding some autocomplete on a form alter. The problem is that in the callback, only the string in the textfield The autocomplete is on, is available. I also want to access a value from another textfield in the callback. How is this possible ?
/**
* Implements hook_form_alter().
*/
function webform_conversion_jquery_form_webform_client_form_1_alter(&$form, &$form_state, $form_id) {
//Load some extra function to process data
module_load_include('inc', 'webform_conversion_jquery', '/includes/dataqueries');
//Add extra js files
drupal_add_js(drupal_get_path('module', 'webform_conversion_jquery') . '/js/conversionform.js');
$form['submitted']['correspondentadress']['cor_street']['#autocomplete_path'] = 'conversionform/conversion_street';
}
}
/**
* Implements hook_menu().
*/
function webform_conversion_jquery_menu() {
$items = array();
$items['conversionform/conversion_street'] = array(
'title' => 'Conversion street autocomplete',
'page callback' => 'conversion_street_autocomplete',
'access callback' => 'user_access',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Retrieve a JSON object containing autocomplete suggestions for streets depending on the zipcode.
*/
function conversion_street_autocomplete($street = '') {
$street = "%" . $street . "%";
$matches = array();
$result = db_select('conversion_adresslist')
->fields('conversion_adresslist', array('street'))
->condition('street', $street, 'like')
->execute();
foreach ($result as $street) {
$matches[$street->street] = $street->street;
}
drupal_json_output($matches);
}
I just want to be able to post extra information in the function:
conversion_street_autocomplete($street = '', $extraparameter)
I had the same problem and have figured out a way, which is not too strenuous. It involves overriding the textfield theme and then passing your parameter to the theme function.
First create declare your theme function:
function mymodule_theme() {
$theme_hooks = array(
'my_module_autocomplete' => array(
'render element' => 'element',
),
);
return $theme_hooks;
}
Next we need to add the theme and the variable to our form element. In my case, the form element is part of a field widget:
function my_module_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
if($instance['widget']['type'] == 'my_module_field_type') {
$element['my_module_field'] = array(
'#type' => 'textfield',
'#autocomplete_path' => 'my-module/autocomplete',
// THIS IS THE IMPORTANT PART - ADD THE THEME AND THE VARIABLE.
'#theme' => 'my_module_autocomplete',
'#my_module_variable' => $field['field_name'],
);
}
return $element;
}
Then implement the theme function. This is a copy of theme_textfield from includes/form.inc with one important difference - we append the variable to the autocomplete path:
function theme_my_module_autocomplet($variables) {
$element = $variables['element'];
$element['#attributes']['type'] = 'text';
element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
_form_set_class($element, array('form-text'));
$extra = '';
if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
drupal_add_library('system', 'drupal.autocomplete');
$element['#attributes']['class'][] = 'form-autocomplete';
$attributes = array();
$attributes['type'] = 'hidden';
$attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
// THIS IS THE IMPORTANT PART. APPEND YOUR VARIABLE TO THE AUTOCOMPLETE PATH.
$attributes['value'] = url($element['#autocomplete_path'] . '/' . $element['#my_module_variable'], array('absolute' => TRUE));
$attributes['disabled'] = 'disabled';
$attributes['class'][] = 'autocomplete';
$extra = '<input' . drupal_attributes($attributes) . ' />';
}
$output = '<input' . drupal_attributes($element['#attributes']) . ' />';
return $output . $extra;
}
Now the variable will be available as the first parameter on the autocomplete callback function:
function _my_module_autocomplete($my_module_variable, $search_string) {
// Happy days, we now have access to our parameter.
}
Just in case anyone is still having trouble with this I found a great solution while trying to figure out how to do this. I had a year select list and that dictated what data was displayed in the autocomplete field. The solution basically has an ajax callback function for the select list that can then update the autocomplete field with an extra parameter in the url. Anyways, it is really well explained in the following article.
http://complexdan.com/passing-custom-arguments-drupal-7-autocomplete/
*A note of caution, I was going crazy trying to figure out why it did not work and it turns out you can't have the same form on the page twice (I needed to because I was displaying it differently for mobile devices) because you are using an id for the ajax callback. I added an extra argument to accomplish that. It is called uniqueid in the below example.
function report_cards_comparison_form($form, &$form_state, $uniqueid) {
$curryear = t('2012');
$form['year_select'] = array(
'#title' => t('School Year'),
'#type' => 'select',
'#options' => array(
'2012' => t('2012'),
'2013' => t('2013'),
'2014' => t('2014'),
'2015' => t('2015'),
),
'#default_value' => $curryear,
'#ajax' => array(
'callback' => 'report_cards_comparison_form_callback',
'wrapper' => $uniqueid,
'progress' => array(
'message' => 'Updating Schools...',
'type' => 'throbber'
),
),
);
$form['choice'] = array(
//'#title' => t('Search By: School Name'),
'#type' => 'textfield',
'#attributes' => array(
'class' => array('school-choice'),
'placeholder' => t('Start Typing School Name...'),
),
'#required' => TRUE,
'#autocomplete_path' => 'reportcards/autocomplete/' . $curryear,
'#prefix' => '<div id="' . $uniqueid . '">',
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'submit',
'#prefix' => '<div class="submit-btn-wrap">',
'#suffix' => '</div>',
'#value' => t('Search'),
'#attributes' => array('id' => 'add-school-submit'),
);
return $form;
}
/**
* Ajax Callback that updates the autocomplete ajax when there is a change in the Year Select List
*/
function report_cards_comparison_form_callback($form, &$form_state) {
unset($form_state['input']['choice'], $form_state['values']['choice']);
$curryear = $form_state['values']['year_select'];
$form_state['input']['choice'] = '';
$form['choice']['#value'] = '';
$form['choice']['#autocomplete_path'] = 'reportcards/autocomplete/' . $curryear;
return form_builder($form['#id'], $form['choice'], $form_state);
}
and I can call the form by doing this...
print render(drupal_get_form('report_cards_comparison_form', 'desktop-schoolmatches'));
You can do it by overriding methods from autocomplete.js in your own js. Here is example:
(function($) {
Drupal.behaviors.someModuleOverrideAC = {
attach: function(context, settings) {
// Next is copied and adjusted method from autocomplete.js
Drupal.jsAC.prototype.populatePopup = function() {
var $input = $(this.input);
var position = $input.position();
// Show popup.
if (this.popup) {
$(this.popup).remove();
}
this.selected = false;
this.popup = $('<div id="autocomplete"></div>')[0];
this.popup.owner = this;
$(this.popup).css({
top: parseInt(position.top + this.input.offsetHeight, 10) + 'px',
left: parseInt(position.left, 10) + 'px',
width: $input.innerWidth() + 'px',
display: 'none'
});
$input.before(this.popup);
// Do search.
this.db.owner = this;
if ($input.attr('name') === 'field_appartment_complex') {
// Overriden search
// Build custom search string for apartments autocomplete
var $wrapper = $('div.apartments-autocomplete');
var $elements = $('input, select', $wrapper);
var searchElements = {string: this.input.value};
$elements.each(function() {
searchElements[$(this).data('address-part')] = $(this).val();
});
var string = encodeURIComponent(JSON.stringify(searchElements));
this.db.search(string);
}
else {
// Default search
this.db.search(this.input.value);
}
};
}
};
}(jQuery));
In your server callback:
function some_module_autocomplete_ajax($string) {
// Decode custom string obtained using overriden autocomplete js.
$components = drupal_json_decode(rawurldecode($string));
// Do you search here using multiple params from $components
}
Ok, for as far as I can see it is not possible. maybe you can roll your own with the ajax functionality in fapi http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#ajax
For now I solved it by implementing jquery.ui.autocomplete which is included in drupal 7