You need to implement this in a custom module, here is a sample code to achieve this:
function custom_node_validate($node, $form) {
if ($node->type == 'page') {
//retrieve the value for your field using Entity API
$wrapper = entity_metadata_wrapper('node', $node);
$value = $wrapper->field_collection->field_unique->value();
//Execute a count query to see if there's other similar values.
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'field_collection_item')
->fieldCondition('field_unique', 'value', $value)
->count();
$count = $query->execute();
if ($count > 1) {
form_set_error('field_unique', 'Unique field value is already used.');
}
}
}
A few disclaimers:
- I am really stocked by the complexity of
FieldField Collection API and it was pretty complicated to find good information about how to retrieve values and make queries. - I really enjoy doing SQL queries (see How to change the legnth of field settingsHow to change the legnth of field settings) but I tried to only use the API instead of doing a simple query on the table
field_data_field_unique
. However it may not yet be perfect so please feel free to chime in. - The form_set_error() isn't highliting the field, I was unable to find the correct name.
Here are the documentation I used:
- hook_node_validate()
- Get value of a field collection field (answer from fago), the Entity API module and entity_metadata_wrapper().
- Checking out EntityFieldQuery (by Ryan Szrama) and the API.
Edit: Following chx advice, to pass directly field_name
to fieldCondition()
.