Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ajax Callbacks in Drupal Forms API
<?php
function partners_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
if ($entity_type != 'field_collection_item' || $entity->field_name != 'field_partner_products') {
return;
}
$form['#after_build'][] = 'partners_products_after_build';
$id = drupal_html_id('partners_field');
$form['#prefix'] = '<div id="'. $id .'">';
$form['#suffix'] = '</div>';
$form['field_partner_product'][LANGUAGE_NONE]['#ajax'] = array(
'callback' => 'partners_field_ajax_callback',
'wrapper' => $id,
);
}
function partners_products_after_build($form, &$form_state) {
if (empty($form['field_partner_product'][LANGUAGE_NONE]['#value'])) {
$form['field_partner_specialisaties']['#access'] = FALSE;
$form['field_partner_certificaties']['#access'] = FALSE;
} else {
if (is_array($form['field_partner_product'][LANGUAGE_NONE]['#value'])) {
$value = !empty($form['field_partner_product'][LANGUAGE_NONE]['#value'][0]) ? $form['field_partner_product'][LANGUAGE_NONE]['#value'][0] : FALSE;
} else {
$value = $form['field_partner_product'][LANGUAGE_NONE]['#value'];
}
if (!empty($value)) {
$tids = partners_get_tids_for_pid($value);
$tids = $tids ? $tids : array();
foreach (array('field_partner_specialisaties','field_partner_certificaties') as $spec_field) {
if ($tids) {
foreach (array_keys($form[$spec_field][LANGUAGE_NONE]['#options']) as $tid) {
if (!in_array($tid, $tids)) {
// unset($form[$spec_field][LANGUAGE_NONE]['#options'][$tid]);
if (!empty($form[$spec_field][LANGUAGE_NONE][$tid])) {
$form[$spec_field][LANGUAGE_NONE][$tid]['#access'] = FALSE;
}
}
}
} else {
$form[$spec_field][LANGUAGE_NONE]['#access'] = FALSE;
}
}
}
}
return $form;
}
function partners_field_ajax_callback($form, $form_state) {
$delta = $form_state['triggering_element']['#parents'][2];
hide($form['field_partner_products'][LANGUAGE_NONE][$delta]['_weight']);
return $form['field_partner_products'][LANGUAGE_NONE][$delta];
}
function partners_get_tids_for_pid($product_id) {
$partner_specialisaties = taxonomy_vocabulary_machine_name_load('partner_specialisaties');
$partner_certificaties = taxonomy_vocabulary_machine_name_load('partner_certificaties');
if (empty($product_id)) {
return;
}
// Query all taxonomy terms with selected product id and Put access true on all of these
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', array($partner_specialisaties->vid, $partner_certificaties->vid), 'IN' )
->fieldCondition('field_partner_product', 'value', $product_id, '=')
->range(0,10);
$result = $query->execute();
if (empty($result)) {
return;
}
$tids = array();
foreach ($result['taxonomy_term'] as $tid => $term) {
$tids[] = $tid;
}
return $tids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment