Active
Project:
Entity reference trim
Component:
Code
Priority:
Normal
Category:
Task
Assigned:
Unassigned
Reporter:
Created:
9 Apr 2014 at 11:05 UTC
Updated:
9 Apr 2014 at 11:05 UTC
This module is great and really required. It would be very cool, if this could be an option integrated in entityreference in the future or become a full project release.
Now some improvements I made when using this module:
function entityreference_trim_field_widget_form_alter(&$element, &$form_state, $context) {
if (isset($element['target_id'])) {
$instance = field_info_instance($element['target_id']['#entity_type'], $element['target_id']['#field_name'], $element['target_id']['#bundle']);
if ($instance['widget']['type'] == 'entityreference_autocomplete') {
drupal_add_js(drupal_get_path('module', 'entityreference_trim') . '/js/entityreference_trim.js');
if ($element['target_id']['#default_value']) {
preg_match("/.+\((\d+)\)/", $element['target_id']['#default_value'], $matches);
$element['target_id']['#hidden_target_id'] = $matches[1];
$element['target_id']['#default_value'] = trim(str_replace('(' . $matches[1] . ')', '', $element['target_id']['#default_value']));
}
// ######## change: I've added this because otherwise the module does not work for fields that don't have a default value set ##############
else {
$element['target_id']['#hidden_target_id'] = $element['target_id']['#default_value'];
}
$element['target_id']['#element_validate'][0] = '_entityreference_trim_autocomplete_validate';
}
}
}
And
/**
* validation callback for entityreference_autocomplete.
*/
function _entityreference_trim_autocomplete_validate($element, &$form_state, $form) {
$elementId = $element['#id'];
// if a value was entered into the autocomplete...
$value = '';
$target_id = isset($form_state['input'][$elementId]) ? drupal_explode_tags($form_state['input'][$elementId]) : 0;
if (!empty($element['#value'])) {
$value = $target_id ? $target_id[0] : $element['#hidden_target_id'];
}
// ######### change: Verify that the selected entity value truely exists!! Use the logic fom entityreference.module for that #########
// Check if the value of the field truely exists!
$field = field_info_field($element['#field_name']);
$handler = entityreference_get_selection_handler($field);
$field_name = $element['#field_name'];
$field = field_info_field($field_name);
$instance = field_info_instance($element['#entity_type'], $field_name, $element['#bundle']);
$handler = entityreference_get_selection_handler($field, $instance);
$handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form);
// update the value of this element so the field can validate the product IDs.
form_set_value($element, $value, $form_state);
}
Please have a look and feel free to integrate this, if you aggree it makes sense.
Both things work great in my case.