updated some more modules
This commit is contained in:
@@ -1,57 +1,52 @@
|
||||
ACKNOWLEDGEMENTS
|
||||
|
||||
As this is the next evolution of Corresponding Node References,
|
||||
I would like to say thanks for all the work done over on Corresponding Node
|
||||
References.
|
||||
This is the next generation of Corresponding Node References. So, thanks are due
|
||||
to everyone who ever worked on CNR!
|
||||
|
||||
DESCRIPTION
|
||||
|
||||
It syncs the entity reference between two entity types which have an entity
|
||||
reference to each other, so double editing entities is no longer needed. If one
|
||||
entity has a reference, the other entity also receives a reference to the saved
|
||||
entity if it is referenced in that entity.
|
||||
CER keeps reference fields in sync. If entity Alice references entity Bob, CER will make Bob back-reference Alice automatically, and it will continue to keep the two in sync if either one is changed or deleted. CER does this by way of “presets”, which are relationships you set up between reference-type fields.
|
||||
|
||||
By “reference-type fields”, I mean any kind of field that references an entity. Out of the box, CER can integrate with the following field types:
|
||||
|
||||
- Entity Reference
|
||||
- Node Reference
|
||||
- User Reference
|
||||
- Taxonomy Term Reference
|
||||
- Profile2 (using the cer_profile2 add-on module)
|
||||
- Commerce Product Reference (using the cer_commerce add-on module)
|
||||
|
||||
CER has an object-oriented API you can use to integrate other kinds of fields, if you need to. For more information, see cer.api.php.
|
||||
|
||||
DEPENDENCIES
|
||||
|
||||
7.x: Entity Reference
|
||||
- Entity API
|
||||
- CTools
|
||||
- Table Element
|
||||
|
||||
EXAMPLE
|
||||
CREATING PRESETS
|
||||
|
||||
Entity type A has an entity reference to entity type B and entity type B has an
|
||||
entity reference to entity type A. When you create entity X of type A and
|
||||
reference it to entity Y of type B entity Y will also receive an update in its
|
||||
entity reference field pointing to entity X.
|
||||
CER won’t do anything until you create at least one preset. To create a preset, visit admin/config/content/cer and click “Add a preset”. You will need Hierarchical Select installed to continue.
|
||||
|
||||
KNOWN ISSUES
|
||||
Select the field you want to use for the left side of the preset, then click Continue. Another select field will appear; use it to choose the field to use for the right side of the preset. Click Save, and you’re all set!
|
||||
|
||||
- Support for entity reference fields in field collections is still a work in progress.
|
||||
CER has no native support for entities that are wrapped by other entities (i.e.,
|
||||
field collections), and implementing this properly will require extensive changes
|
||||
to many parts of CER. For this reason, field collection support is on hold until
|
||||
a few other major issues in the queue are sorted out. The thread for field collection
|
||||
support is http://drupal.org/node/1729666.
|
||||
THINGS YOU SHOULD KNOW
|
||||
|
||||
- Support for multi-language entities is, at the time of this writing, flaky at best.
|
||||
There is a patch to implement better multi-language support, available at
|
||||
http://drupal.org/node/1961026. If this patch works well for you, PLEASE post
|
||||
in that issue to say that it worked so that the patch can be reviewed by
|
||||
the community before being committed into CER.
|
||||
* If you’re updating from CER 1.x or 2.x, you MUST clear all your caches *before* running update.php so that new classes can be registered with the autoloader! If you don’t do this, you are likely to receive fatal errors during the update.
|
||||
|
||||
- If you're updating CER from 1.x to 2.x, you should rebuild your theme registry.
|
||||
This is because the reference labels on CER's admin page were made themeable
|
||||
in 2.x, so you'll need to make Drupal recognize the new theme hook.
|
||||
* If you have Corresponding Node References installed, CER will disable it and take over its field relationships.
|
||||
|
||||
INSTALL
|
||||
* Everything CER does, it does in a normal security context. This can lead to unexpected behavior if you’re not aware of it. In other words, if you don’t have the permission to view a specific node, don’t expect CER to be able to reference it when logged in as you. Be mindful of your entity/field permissions!
|
||||
|
||||
* devel_generate does not play nicely with CER, especially where field collections are concerned. The results are utterly unpredictable.
|
||||
|
||||
- To install enable the module at admin/build/modules
|
||||
- Create entity type A
|
||||
- Create entity type B
|
||||
- Create a entity reference field on entity type A pointing to entity B
|
||||
- Create a entity reference field on entity type B pointing to entity A
|
||||
- Go to the settings page at admin/config/system/cer.
|
||||
Select to enable the corresponding referencing for these node types pointing
|
||||
to each other.
|
||||
- Create some entities and reference them to each other
|
||||
ROAD MAP
|
||||
|
||||
If any of this stuff interests you, I wholeheartedly encourage you to submit patches or contribute in any way you can!
|
||||
|
||||
- Moar automated test coverage
|
||||
- Performance enhancement
|
||||
- Documentation
|
||||
|
||||
MAINTAINER
|
||||
|
||||
|
||||
@@ -1,111 +1,88 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Administrative functionality, separated for performance purposes.
|
||||
* Form builder to create or edit presets.
|
||||
*/
|
||||
function cer_form(array $form, array &$form_state, CerPreset $preset, $do = 'edit', $entity_type = NULL) {
|
||||
field_attach_form('cer', $preset, $form, $form_state);
|
||||
|
||||
/**
|
||||
* The settings form.
|
||||
*/
|
||||
function cer_settings_form($form = array(), &$form_state) {
|
||||
$channels = array();
|
||||
$form['cer_right']['#id'] = 'edit-cer-right';
|
||||
|
||||
foreach (_cer_get_fields() as $field) {
|
||||
// A field that hasn't been instantiated yet will not have a 'bundles' key, which
|
||||
// means it's useless to us, so skip over it.
|
||||
if (! isset($field['bundles'])) {
|
||||
continue;
|
||||
}
|
||||
$form['cer_left'][LANGUAGE_NONE]['#ajax'] = array(
|
||||
'callback' => 'cer_update_right',
|
||||
'wrapper' => $form['cer_right']['#id'],
|
||||
);
|
||||
|
||||
foreach ($field['bundles'] as $entity_type => $bundles) {
|
||||
foreach ($bundles as $bundle) {
|
||||
$instance = field_info_instance($entity_type, $field['field_name'], $bundle);
|
||||
if ($instance) {
|
||||
$channels = array_merge($channels, _cer_find_channels($instance));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($channels)) {
|
||||
drupal_set_message(t('There are no entity reference fields that can correspond.'), 'warning');
|
||||
}
|
||||
else {
|
||||
$mapping = array();
|
||||
foreach ($channels as $count => $key) {
|
||||
$formatted_key = str_replace(' ', '*', $key);
|
||||
|
||||
$mapping[$count] = $formatted_key;
|
||||
|
||||
$form['values']["enabled_{$count}"] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#default_value' => cer_preset_enabled($formatted_key),
|
||||
'#title' => filter_xss(theme('cer_label', array('key' => $key))),
|
||||
);
|
||||
}
|
||||
|
||||
// We are using a hidden field to submit the configuration because on
|
||||
// some systems the checkbox name length is limited, and using
|
||||
// the key would cause the length to be too long. (Issue #558612)
|
||||
$form['mapping'] = array(
|
||||
'#type' => 'hidden',
|
||||
'#value' => serialize($mapping),
|
||||
);
|
||||
|
||||
$form['submit'] = array(
|
||||
$form['actions'] = array(
|
||||
'submit' => array(
|
||||
'#type' => 'submit',
|
||||
'#value' => t('Save'),
|
||||
);
|
||||
}
|
||||
|
||||
),
|
||||
'#weight' => 10,
|
||||
);
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
function cer_form_submit(array &$form, array &$form_state) {
|
||||
$preset = entity_ui_form_submit_build_entity($form, $form_state)->save();
|
||||
|
||||
drupal_set_message(t('The preset has been saved.'));
|
||||
$form_state['redirect'] = 'admin/config/content/cer';
|
||||
}
|
||||
|
||||
function cer_update_right(array &$form, array &$form_state) {
|
||||
$preset = $form_state['build_info']['args'][0];
|
||||
field_attach_submit('cer', $preset, $form, $form_state, array('field_name' => 'cer_left'));
|
||||
|
||||
$left = $preset->wrapper->cer_left->chain->value();
|
||||
$left_identifier = $left->__toString();
|
||||
$left_re = $left->regex();
|
||||
|
||||
$hierarchy = new FieldHierarchy();
|
||||
foreach (CerFieldChain::collectAll() as $chain) {
|
||||
if (preg_match($left_re, $chain->__toString()) && preg_match($chain->regex(), $left_identifier)) {
|
||||
$hierarchy->addChain($chain);
|
||||
}
|
||||
}
|
||||
|
||||
$options = $hierarchy->options();
|
||||
if ($options) {
|
||||
$form['cer_right'][LANGUAGE_NONE]['#options'] = $options;
|
||||
}
|
||||
else {
|
||||
drupal_set_message(t('There are no fields which can correspond with your selection.'), 'warning');
|
||||
}
|
||||
|
||||
return $form['cer_right'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit function for settings form.
|
||||
* Enables or disables a preset, depending on its current status. This callback
|
||||
* is defined by CerUIController::hook_menu().
|
||||
*/
|
||||
function cer_settings_form_submit($form, $form_state) {
|
||||
ctools_include('export');
|
||||
$query_values = array();
|
||||
function cer_toggle_preset(CerPreset $preset) {
|
||||
$preset->wrapper->cer_enabled->set(! $preset->wrapper->cer_enabled->value());
|
||||
$preset->save();
|
||||
|
||||
$mapping = unserialize($form_state['values']['mapping']);
|
||||
drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : 'admin/config/content/cer');
|
||||
}
|
||||
|
||||
foreach ($form_state['values'] as $key => $value) {
|
||||
$keys = explode('_', $key);
|
||||
if ($keys[0] == 'enabled') {
|
||||
$query_values[$mapping[$keys[1]]] = $value;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Permanently inverts a preset (i.e., deletes the original). This callback
|
||||
* is defined by CerUIController::hook_menu().
|
||||
*/
|
||||
function cer_invert_preset(CerPreset $original) {
|
||||
$original->invert()->save();
|
||||
$original->delete();
|
||||
|
||||
// load all existing presets
|
||||
$presets = ctools_export_crud_load_all('cer');
|
||||
|
||||
foreach ($query_values as $key => $value) {
|
||||
// get preset object (create new one if it doesn't exist already).
|
||||
$preset = empty($presets[$key]) ? ctools_export_crud_new('cer') : $presets[$key];
|
||||
|
||||
// set and save value
|
||||
if (empty($preset->entity_types_content_fields)) {
|
||||
$preset->entity_types_content_fields = $key;
|
||||
}
|
||||
$preset->enabled = $value;
|
||||
ctools_export_crud_save('cer', $preset);
|
||||
|
||||
// remove from list of presets, so we know which ones are still used
|
||||
if (isset($presets[$key])) {
|
||||
unset($presets[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
drupal_set_message(t('The configuration has been saved.'));
|
||||
drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : 'admin/config/content/cer');
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows batch updating of existing entities.
|
||||
*/
|
||||
function cer_update_form($form = array(), &$form_state) {
|
||||
function cer_bulk_update_form(array $form, array &$form_state) {
|
||||
$form['type'] = array(
|
||||
'#type' => 'select',
|
||||
'#title' => t('Entity type'),
|
||||
@@ -126,152 +103,31 @@ function cer_update_form($form = array(), &$form_state) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The update form.
|
||||
* Allows updating of current entitys.
|
||||
* The update form. Allows bulk updating of current entities.
|
||||
*/
|
||||
function cer_update_form_submit($form, &$form_state) {
|
||||
function cer_bulk_update_form_submit(array $form, array &$form_state) {
|
||||
$batch = array(
|
||||
'finished' => 'cer_batch_update_existing_finished',
|
||||
'title' => t('Processing'),
|
||||
'init_message' => t('Preparing to update corresponding entity references for existing entities...'),
|
||||
'progress_message' => t('Processing entities...'),
|
||||
'error_message' => t('Corresponding entity references - existing entity update has encountered an error.'),
|
||||
'operations' => array(),
|
||||
);
|
||||
|
||||
$entity_type = $form_state['values']['type'];
|
||||
$query = new EntityFieldQuery();
|
||||
$query->entityCondition('entity_type', $entity_type);
|
||||
if ($entity_type == 'user') {
|
||||
$query->entityCondition('entity_id', 0, '>');
|
||||
}
|
||||
$result = $query->execute();
|
||||
|
||||
if (isset($result[$entity_type])) {
|
||||
foreach ($result[$entity_type] as $entity_id => $stub) {
|
||||
foreach (array_keys($result[$entity_type]) as $entity_id) {
|
||||
$batch['operations'][] = array('cer_processing_entity', array('update', $entity_id, $entity_type));
|
||||
}
|
||||
}
|
||||
|
||||
batch_set($batch);
|
||||
}
|
||||
|
||||
/**
|
||||
* The purpose of this function is to answer this question: I am a field instance. Which other
|
||||
* fields reference the entity that owns me? And of those instances, which ones can I reference?
|
||||
* The answer is returned as an array of CER keys: "entity1 bundle1 field1 entity2 bundle2 field2".
|
||||
*
|
||||
* @param array $instance
|
||||
* Field instance info, as returned by field_info_instance().
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function _cer_find_channels($instance) {
|
||||
$channels = array();
|
||||
|
||||
$my_id = $instance['entity_type'] . ' ' . $instance['bundle'] . ' ' . $instance['field_name'];
|
||||
$my_info = field_info_field($instance['field_name']);
|
||||
$my_targets = _cer_get_target_bundles($my_info);
|
||||
$my_target_type = $my_info['settings']['target_type'];
|
||||
|
||||
$referrers = _cer_find_referrers($instance['entity_type'], $instance['bundle']);
|
||||
foreach ($referrers as $referrer) {
|
||||
if (isset($referrer['bundles'][$my_target_type])) {
|
||||
if (empty($my_targets)) {
|
||||
$bundles = $referrer['bundles'][$my_target_type];
|
||||
}
|
||||
else {
|
||||
$bundles = array_intersect($referrer['bundles'][$my_target_type], $my_targets);
|
||||
}
|
||||
|
||||
foreach ($bundles as $bundle) {
|
||||
$channels[] = "{$my_id} {$my_target_type} {$bundle} " . $referrer['field_name'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $channels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all fields that can reference the given entity type and bundle.
|
||||
*
|
||||
* @param $entity_type
|
||||
* The entity type that can be referenced.
|
||||
* @param $bundle
|
||||
* The bundle that can be referenced.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function _cer_find_referrers($entity_type, $bundle) {
|
||||
$referrers = array();
|
||||
foreach (_cer_get_fields() as $field) {
|
||||
if ($field['settings']['target_type'] == $entity_type) {
|
||||
$target_bundles = _cer_get_target_bundles($field);
|
||||
if (empty($target_bundles) || in_array($bundle, $target_bundles)) {
|
||||
$referrers[] = $field;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $referrers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all bundles reference-able by a given field. If all bundles are reference-able,
|
||||
* an empty array is returned.
|
||||
*
|
||||
* @param $field
|
||||
* Field info array as returned by field_info_field().
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function _cer_get_target_bundles($field) {
|
||||
$target_bundles = array();
|
||||
|
||||
// If the reference field is using a view, load the view and see if it's filtering by the entity
|
||||
// type's bundle filter. If it is, the filter values are the target bundles. Otherwise,
|
||||
// assume that all bundles can be referenced.
|
||||
//
|
||||
// @todo Support contextual filters?
|
||||
//
|
||||
// NOTE: Selection handlers (i.e., $field['settings']['handler']) are plugins owned by
|
||||
// Entity Reference. There is no method defined to get an array of referenceable
|
||||
// bundles, but hopefully, if CER gains enough traction in the community, such a
|
||||
// method can be added to the EntityReference_SelectionHandler interface. This
|
||||
// function could then be deprecated, which would be a more flexible, future-proof
|
||||
// method of finding a field's target bundles.
|
||||
//
|
||||
if ($field['settings']['handler'] == 'views') {
|
||||
$view_name = $field['settings']['handler_settings']['view']['view_name'];
|
||||
|
||||
$view = views_get_view($view_name);
|
||||
if ($view) {
|
||||
$view->set_display($field['settings']['handler_settings']['view']['display_name']);
|
||||
|
||||
$info = entity_get_info($field['settings']['target_type']);
|
||||
if ($info['entity keys']['bundle'] && $handler = $view->display_handler->get_handler('filter', $info['entity keys']['bundle'])) {
|
||||
$target_bundles = $handler->value;
|
||||
}
|
||||
}
|
||||
else {
|
||||
drupal_set_message(t('Could not get target bundles for %field (failed to load view %view).', array('%view' => $view_name, '%field' => $field['field_name'])), 'error');
|
||||
}
|
||||
}
|
||||
elseif (isset($field['settings']['handler_settings']['target_bundles'])) {
|
||||
$target_bundles = $field['settings']['handler_settings']['target_bundles'];
|
||||
}
|
||||
else {
|
||||
$info = entity_get_info($field['settings']['target_type']);
|
||||
$target_bundles = array_keys($info['bundles']);
|
||||
}
|
||||
|
||||
return $target_bundles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Field API definitions for all entity reference fields.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function _cer_get_fields() {
|
||||
static $fields;
|
||||
if (!isset($fields)) {
|
||||
$fields = array_map('field_info_field', db_select('field_config', 'fc')->fields('fc', array('field_name'))->condition('type', 'entityreference')->execute()->fetchCol());
|
||||
}
|
||||
return $fields;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* In order to create relationships between reference fields, CER needs to know
|
||||
* about what reference fields are available, and how to handle them, which is
|
||||
* what this hook is for. It should always return an array, even if there are
|
||||
* no fields to expose. The ultimate goal of this hook is to define a flattened
|
||||
* hierarchy of all the reference-type fields that CER can use.
|
||||
*
|
||||
* A reference-type field is any type of field that can refer to an entity.
|
||||
* This is pretty broadly defined: for example, CER considers field collections
|
||||
* to be reference-type fields, since they refer to entities of the
|
||||
* field_collection_item type. Even though the field collection may be displayed
|
||||
* as an embedded part of its host entity, at heart it's still just a reference
|
||||
* to an entity.
|
||||
*/
|
||||
function hook_cer_fields() {
|
||||
return array(
|
||||
// The keys should refer to a single field instance on a single bundle of a single
|
||||
// entity type, even for embedded entities like field collections (see below).
|
||||
'node:article:field_related_pages' => array(
|
||||
// At the very least, each field you return here needs to have a 'class' set,
|
||||
// which is the class of the plugin which will handle this field. A CER field
|
||||
// plugin must be a sub-class of CerField, and there must be a separate plugin
|
||||
// for each *type* of field you want to integrate (CER provides support for
|
||||
// most reference-type fields out of the box, though). The class you provide
|
||||
// MUST be registered with the autoloader (i.e., you need to mention it in the
|
||||
// files[] array in your module's info file).
|
||||
'class' => 'CerEntityReferenceField',
|
||||
),
|
||||
// A field collection field is a type of reference field, so you can expose these
|
||||
// to CER too. If you want to refer to reference fields on field collections, you
|
||||
// must define the parent fields too, as in this example.
|
||||
'node:page:field_my_field_collection' => array(
|
||||
'class' => 'CerFieldCollectionField',
|
||||
),
|
||||
'field_collection_item:field_my_field_collection:field_related_articles' => array(
|
||||
'class' => 'CerEntityReferenceField',
|
||||
// For fields that are embedded in other entities (the prime example being field
|
||||
// collections), the possible parents of the field need to be defined. The array
|
||||
// of parents should be an array of keys that are present in the aggregated result
|
||||
// of hook_cer_fields(). There could be many possible parents for a single field;
|
||||
// each parent represents another possible "route" to this field. If you leave
|
||||
// this out, CER will try to automatically detect the parents.
|
||||
'parents' => array(
|
||||
'node:page:field_my_field_collection',
|
||||
),
|
||||
// Embedded fields might *require* a parent. At the time of this writing, this
|
||||
// really only applies to field collections. The "require parent" flag means that
|
||||
// this field MUST have at least one parent, or CER won't use it. You can probably
|
||||
// omit this key, and let CER detect the correct value.
|
||||
'require parent' => TRUE,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alter the information gathered by hook_cer_fields().
|
||||
*/
|
||||
function hook_cer_fields_alter(array &$fields) {
|
||||
// Do clever things here.
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains CER hook implementations.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implements hook_cer_fields().
|
||||
*/
|
||||
function cer_cer_fields() {
|
||||
$fields = array();
|
||||
|
||||
if (module_exists('taxonomy')) {
|
||||
$fields = array_merge($fields, _cer_collect_fields_of_type('taxonomy_term_reference', 'CerTaxonomyTermReferenceField'));
|
||||
}
|
||||
if (module_exists('entityreference')) {
|
||||
$fields = array_merge($fields, _cer_collect_fields_of_type('entityreference', 'CerEntityReferenceField'));
|
||||
}
|
||||
if (module_exists('node_reference')) {
|
||||
$fields = array_merge($fields, _cer_collect_fields_of_type('node_reference', 'CerNodeReferenceField'));
|
||||
}
|
||||
if (module_exists('user_reference')) {
|
||||
$fields = array_merge($fields, _cer_collect_fields_of_type('user_reference', 'CerUserReferenceField'));
|
||||
}
|
||||
if (module_exists('field_collection')) {
|
||||
$fields = array_merge($fields, _cer_collect_fields_of_type('field_collection', 'CerFieldCollectionField'));
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implmements hook_cer_fields_alter().
|
||||
*/
|
||||
function cer_cer_fields_alter(array &$fields) {
|
||||
foreach (array_keys($fields) as $identifier) {
|
||||
list ($entity_type, $bundle, $field) = explode(':', $identifier);
|
||||
|
||||
if ($entity_type == 'field_collection_item') {
|
||||
$result = db_query("SELECT entity_type, bundle, field_name FROM {field_config_instance} WHERE field_name = :field_collection", array(':field_collection' => $bundle));
|
||||
|
||||
foreach ($result as $r) {
|
||||
$fields[$identifier]['parents'][] = "{$r->entity_type}:{$r->bundle}:{$r->field_name}";
|
||||
}
|
||||
|
||||
$fields[$identifier]['require parent'] = TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _cer_collect_fields_of_type($field_type, $class) {
|
||||
$fields = array();
|
||||
|
||||
$result = db_query("SELECT fci.entity_type, fci.bundle, fci.field_name FROM {field_config_instance} fci INNER JOIN {field_config} fc ON fc.id = fci.field_id WHERE fc.type = :type AND fc.deleted = 0 AND fci.deleted = 0", array(':type' => $field_type));
|
||||
foreach ($result as $r) {
|
||||
$fields["{$r->entity_type}:{$r->bundle}:{$r->field_name}"]['class'] = $class;
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
@@ -2,15 +2,37 @@ name = Corresponding Entity References
|
||||
description = Syncs the entity references between entity types which have an entityreference to each other.
|
||||
core = 7.x
|
||||
package = Fields
|
||||
dependencies[] = entityreference
|
||||
configure = admin/config/content/cer
|
||||
|
||||
dependencies[] = ctools
|
||||
dependencies[] = list
|
||||
dependencies[] = entity
|
||||
dependencies[] = field_object
|
||||
dependencies[] = elements
|
||||
|
||||
files[] = handler.inc
|
||||
files[] = includes/CerEndPointIterator.inc
|
||||
files[] = includes/CerEntityContainerInterface.inc
|
||||
files[] = includes/CerField.inc
|
||||
files[] = includes/CerFieldChain.inc
|
||||
files[] = includes/CerFieldChainHandler.inc
|
||||
files[] = includes/CerFieldHandler.inc
|
||||
files[] = includes/CerPreset.inc
|
||||
files[] = includes/CerPresetController.inc
|
||||
files[] = includes/CerPresetFeaturesController.inc
|
||||
files[] = includes/CerPresetFinder.inc
|
||||
files[] = includes/CerPresetHandler.inc
|
||||
files[] = includes/CerUIController.inc
|
||||
files[] = includes/fields/entity_reference.inc
|
||||
files[] = includes/fields/field_collection.inc
|
||||
files[] = includes/fields/node_reference.inc
|
||||
files[] = includes/fields/taxonomy_term_reference.inc
|
||||
files[] = includes/fields/user_reference.inc
|
||||
|
||||
configure = admin/config/system/cer
|
||||
; Information added by Drupal.org packaging script on 2014-08-08
|
||||
version = "7.x-2.x-dev"
|
||||
files[] = tests/CerBasicTestCase.test
|
||||
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1407528862"
|
||||
datestamp = "1455299962"
|
||||
|
||||
|
||||
@@ -9,52 +9,471 @@
|
||||
* Implements hook_schema().
|
||||
*/
|
||||
function cer_schema() {
|
||||
$schema['cer'] = array(
|
||||
'description' => t('Saves the content types and entity reference fields for which the corresponding entity reference is enabled'),
|
||||
$schema = array();
|
||||
|
||||
// @see entity_exportable_schema_fields()
|
||||
$schema['cer_preset'] = array(
|
||||
'fields' => array(
|
||||
'entity_types_content_fields' => array('type' => 'varchar', 'length' => 200, 'not null' => TRUE, 'default' => ''),
|
||||
'enabled' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
|
||||
),
|
||||
'primary key' => array('entity_types_content_fields'),
|
||||
'export' => array(
|
||||
'key' => 'entity_types_content_fields',
|
||||
'status' => 'enabled',
|
||||
'primary key' => 'entity_types_content_fields',
|
||||
'key name' => 'Corresponding entity reference',
|
||||
'identifier' => 'cnr_obj',
|
||||
'api' => array(
|
||||
'api' => 'default_cer_presets',
|
||||
'owner' => 'cer',
|
||||
'minimum_version' => 1,
|
||||
'current_version' => 1,
|
||||
'pid' => array(
|
||||
'type' => 'serial',
|
||||
'not null' => TRUE,
|
||||
),
|
||||
'identifier' => array(
|
||||
'type' => 'text',
|
||||
'size' => 'tiny',
|
||||
'not null' => TRUE,
|
||||
'description' => "The preset's machine-readable export identifier.",
|
||||
),
|
||||
'status' => array(
|
||||
'type' => 'int',
|
||||
'size' => 'tiny',
|
||||
'not null' => TRUE,
|
||||
'default' => 0x01, // ENTITY_CUSTOM
|
||||
'description' => "The preset's exportable status.",
|
||||
),
|
||||
'module' => array(
|
||||
'type' => 'varchar',
|
||||
'length' => 255,
|
||||
'not null' => FALSE,
|
||||
'default' => 'cer',
|
||||
'description' => 'The module, if any, which exports this preset.',
|
||||
),
|
||||
),
|
||||
'primary key' => array('pid'),
|
||||
);
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_install().
|
||||
*/
|
||||
function cer_install() {
|
||||
field_info_cache_clear();
|
||||
$fields = _cer_field_definitions();
|
||||
array_walk($fields, 'field_create_field');
|
||||
$instances = _cer_field_instance_definitions();
|
||||
array_walk($instances, 'field_create_instance');
|
||||
|
||||
if (module_exists('corresponding_node_references')) {
|
||||
_cer_hijack_cnr();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains the default field definitions for presets.
|
||||
*/
|
||||
function _cer_field_definitions() {
|
||||
$field_bases = array();
|
||||
|
||||
$field_bases[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_bidirectional',
|
||||
'foreign keys' => array(),
|
||||
'indexes' => array(
|
||||
'value' => array(
|
||||
0 => 'value',
|
||||
),
|
||||
),
|
||||
'locked' => 0,
|
||||
'module' => 'list',
|
||||
'settings' => array(
|
||||
'allowed_values' => array(
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
),
|
||||
'allowed_values_function' => '',
|
||||
),
|
||||
'translatable' => 0,
|
||||
'type' => 'list_boolean',
|
||||
);
|
||||
|
||||
$field_bases[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_enabled',
|
||||
'foreign keys' => array(),
|
||||
'indexes' => array(
|
||||
'value' => array(
|
||||
0 => 'value',
|
||||
),
|
||||
),
|
||||
'locked' => 1,
|
||||
'module' => 'list',
|
||||
'settings' => array(
|
||||
'allowed_values' => array(
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
),
|
||||
'allowed_values_function' => '',
|
||||
),
|
||||
'translatable' => 0,
|
||||
'type' => 'list_boolean',
|
||||
);
|
||||
|
||||
$field_bases[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_weight',
|
||||
'foreign keys' => array(),
|
||||
'indexes' => array(
|
||||
'value' => array(
|
||||
0 => 'value',
|
||||
),
|
||||
),
|
||||
'locked' => 0,
|
||||
'module' => 'list',
|
||||
'settings' => array(
|
||||
'allowed_values' => array(),
|
||||
'allowed_values_function' => 'cer_weight_options',
|
||||
),
|
||||
'translatable' => 0,
|
||||
'type' => 'list_integer',
|
||||
);
|
||||
|
||||
$field_bases[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_left',
|
||||
'foreign keys' => array(
|
||||
'field_instance' => array(
|
||||
'columns' => array(
|
||||
'fiid' => 'id',
|
||||
),
|
||||
'table' => 'field_config_instance',
|
||||
),
|
||||
),
|
||||
'indexes' => array(),
|
||||
'locked' => 1,
|
||||
'module' => 'field_object',
|
||||
'settings' => array(),
|
||||
'translatable' => 0,
|
||||
'type' => 'field_object',
|
||||
);
|
||||
|
||||
$field_bases[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_right',
|
||||
'foreign keys' => array(
|
||||
'field_instance' => array(
|
||||
'columns' => array(
|
||||
'fiid' => 'id',
|
||||
),
|
||||
'table' => 'field_config_instance',
|
||||
),
|
||||
),
|
||||
'indexes' => array(),
|
||||
'locked' => 1,
|
||||
'module' => 'field_object',
|
||||
'settings' => array(),
|
||||
'translatable' => 0,
|
||||
'type' => 'field_object',
|
||||
);
|
||||
|
||||
return $field_bases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains the default field instance definitions for presets.
|
||||
*/
|
||||
function _cer_field_instance_definitions() {
|
||||
$field_instances = array();
|
||||
|
||||
$field_instances[] = array(
|
||||
'bundle' => 'cer',
|
||||
'default_value' => array(
|
||||
0 => array(
|
||||
'value' => 1,
|
||||
),
|
||||
),
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'above',
|
||||
'module' => 'list',
|
||||
'settings' => array(),
|
||||
'type' => 'list_default',
|
||||
'weight' => 1,
|
||||
),
|
||||
),
|
||||
'entity_type' => 'cer',
|
||||
'field_name' => 'cer_bidirectional',
|
||||
'label' => 'Bidirectional',
|
||||
'required' => 0,
|
||||
'settings' => array(),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(
|
||||
'display_label' => 1,
|
||||
),
|
||||
'type' => 'options_onoff',
|
||||
'weight' => 3,
|
||||
),
|
||||
);
|
||||
|
||||
$field_instances[] = array(
|
||||
'bundle' => 'cer',
|
||||
'default_value' => array(
|
||||
0 => array(
|
||||
'value' => 1,
|
||||
),
|
||||
),
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'above',
|
||||
'module' => 'list',
|
||||
'settings' => array(),
|
||||
'type' => 'list_default',
|
||||
'weight' => 0,
|
||||
),
|
||||
),
|
||||
'entity_type' => 'cer',
|
||||
'field_name' => 'cer_enabled',
|
||||
'label' => 'Enabled',
|
||||
'required' => 0,
|
||||
'settings' => array(),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(
|
||||
'display_label' => 1,
|
||||
),
|
||||
'type' => 'options_onoff',
|
||||
'weight' => 2,
|
||||
),
|
||||
);
|
||||
|
||||
$field_instances[] = array(
|
||||
'bundle' => 'cer',
|
||||
'default_value' => array(
|
||||
0 => array(
|
||||
'value' => 0,
|
||||
),
|
||||
),
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'above',
|
||||
'module' => 'list',
|
||||
'settings' => array(),
|
||||
'type' => 'list_default',
|
||||
'weight' => 4,
|
||||
),
|
||||
),
|
||||
'entity_type' => 'cer',
|
||||
'field_name' => 'cer_weight',
|
||||
'label' => 'Weight',
|
||||
'required' => 1,
|
||||
'settings' => array(),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(),
|
||||
'type' => 'options_select',
|
||||
'weight' => 4,
|
||||
),
|
||||
);
|
||||
|
||||
$field_instances[] = array(
|
||||
'bundle' => 'cer',
|
||||
'default_value' => NULL,
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'hidden',
|
||||
'module' => NULL,
|
||||
'settings' => array(),
|
||||
'type' => 'field_object_default',
|
||||
'weight' => 5,
|
||||
),
|
||||
),
|
||||
'entity_type' => 'cer',
|
||||
'field_name' => 'cer_left',
|
||||
'label' => 'Left Field',
|
||||
'required' => 1,
|
||||
'settings' => array(
|
||||
'function' => 'CerFieldChain::collectAll',
|
||||
),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(),
|
||||
'type' => 'options_select',
|
||||
'weight' => 0,
|
||||
),
|
||||
);
|
||||
|
||||
$field_instances[] = array(
|
||||
'bundle' => 'cer',
|
||||
'default_value' => NULL,
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'hidden',
|
||||
'module' => NULL,
|
||||
'settings' => array(),
|
||||
'type' => 'field_object_default',
|
||||
'weight' => 6,
|
||||
),
|
||||
),
|
||||
'entity_type' => 'cer',
|
||||
'field_name' => 'cer_right',
|
||||
'label' => 'Right Field',
|
||||
'required' => 1,
|
||||
'settings' => array(
|
||||
'function' => 'CerFieldChain::collectAll',
|
||||
),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(),
|
||||
'type' => 'options_select',
|
||||
'weight' => 1,
|
||||
),
|
||||
);
|
||||
|
||||
return $field_instances;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_uninstall().
|
||||
*/
|
||||
function cer_uninstall() {
|
||||
variable_del('cer_debug');
|
||||
|
||||
// Delete fields created by cer_install()
|
||||
field_delete_field('cer_left');
|
||||
field_delete_field('cer_right');
|
||||
field_delete_field('cer_bidirectional');
|
||||
field_delete_field('cer_enabled');
|
||||
field_delete_field('cer_weight');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts all CNR presets to CER presets, then disables CNR.
|
||||
*/
|
||||
function _cer_hijack_cnr() {
|
||||
$cnr = db_query('SELECT * FROM {corresponding_node_references} WHERE 1')->fetchAll();
|
||||
|
||||
foreach ($cnr as $index => $preset) {
|
||||
// Prepend 'node*' to each side of the preset. CNR, sensibly enough, assumes everything
|
||||
// is on a node, but CER needs this specified explicitly.
|
||||
$key = explode('*', $preset->node_types_content_fields);
|
||||
$cnr[$index]->entity_types_content_fields = "node*{$key[0]}*{$key[1]}*node*{$key[2]}*{$key[3]}";
|
||||
}
|
||||
array_walk($cnr, '_cer_rebuild_preset');
|
||||
|
||||
module_disable(array('corresponding_node_references'));
|
||||
drupal_set_message(t('Rebuilt CNR presets.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename table to shorten module name.
|
||||
*/
|
||||
function cer_update_7001() {
|
||||
db_rename_table('corresponding_entity_references', 'cer');
|
||||
if (db_table_exists('corresponding_entity_references')) {
|
||||
db_rename_table('corresponding_entity_references', 'cer');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable presets which refer to fields that don't exist. (Issue #2122531)
|
||||
* Creates the {cer_preset} table to store CerPreset entities, and rebuilds
|
||||
* legacy presets.
|
||||
*/
|
||||
function cer_update_7002() {
|
||||
$presets = db_query('SELECT entity_types_content_fields FROM {cer} WHERE 1')->fetchCol();
|
||||
function cer_update_7005() {
|
||||
// Register new classes with the autoloader.
|
||||
registry_rebuild();
|
||||
|
||||
foreach ($presets as $preset) {
|
||||
$keys = explode('*', $preset);
|
||||
|
||||
$left = field_info_instance($keys[0], $keys[2], $keys[1]);
|
||||
$right = field_info_instance($keys[3], $keys[5], $keys[4]);
|
||||
// Create the table for preset entities.
|
||||
$tables = cer_schema();
|
||||
db_create_table('cer_preset', $tables['cer_preset']);
|
||||
|
||||
if (empty($left) || empty($right)) {
|
||||
db_query('UPDATE {cer} SET enabled = 0 WHERE entity_types_content_fields = :preset', array(':preset' => $preset));
|
||||
drupal_set_message(t('CER preset %preset was disabled because it uses non-existent fields.', array('%preset' => $preset)), 'warning');
|
||||
}
|
||||
// Install Field Reference, which powers the cer_left and cer_right fields.
|
||||
if (! module_exists('field_object')) {
|
||||
module_enable(array('field_object'));
|
||||
}
|
||||
|
||||
// Create preset entities' fields.
|
||||
cer_install();
|
||||
|
||||
// Convert legacy presets to entities, including 1.x, 2.x and the older
|
||||
// 3.x schemas.
|
||||
$old = db_select('cer')->fields('cer')->execute()->fetchAll();
|
||||
$old = array_merge($old, module_invoke_all('cer_default_presets'));
|
||||
array_walk($old, '_cer_rebuild_preset');
|
||||
|
||||
// So long, legacy table...
|
||||
db_drop_table('cer');
|
||||
|
||||
// Delete defunct status variable maintained by CTools.
|
||||
variable_del('default_cer');
|
||||
|
||||
if (module_exists('corresponding_node_references')) {
|
||||
_cer_hijack_cnr();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds a legacy CER or CNR preset as a CerPreset entity.
|
||||
*/
|
||||
function _cer_rebuild_preset($old) {
|
||||
if (isset($old->entity_types_content_fields)) {
|
||||
$keys = explode('*', $old->entity_types_content_fields);
|
||||
|
||||
$old->a = implode(':', array_slice($keys, 0, 3));
|
||||
$old->b = implode(':', array_slice($keys, 3));
|
||||
}
|
||||
if (! isset($old->bidirectional)) {
|
||||
$old->bidirectional = TRUE;
|
||||
}
|
||||
if (! isset($old->weight)) {
|
||||
$old->weight = 0;
|
||||
}
|
||||
// If the 'enabled' flag doesn't exist, we can presume that this preset
|
||||
// was exported in code generated by CTools, which means that it should
|
||||
// have a 'disabled' flag, which we can invert to get the status.
|
||||
if (! isset($old->enabled)) {
|
||||
$old->enabled = (! $old->disabled);
|
||||
}
|
||||
|
||||
// Validate both field chains by trying to unpack them. If any field in
|
||||
// either chain isn't exposed by hook_cer_fields(), an exception will be
|
||||
// thrown and we can bail out with an error message.
|
||||
try {
|
||||
CerFieldChain::unpack($old->a);
|
||||
CerFieldChain::unpack($old->b);
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$variables = array(
|
||||
'%key' => "{$old->a}*{$old->b}",
|
||||
);
|
||||
return drupal_set_message(t('Could not rebuild preset %key because it refers to invalid fields.', $variables), 'error');
|
||||
}
|
||||
|
||||
$preset = new CerPreset();
|
||||
$preset->wrapper->cer_left->set($old->a);
|
||||
$preset->wrapper->cer_right->set($old->b);
|
||||
$preset->wrapper->cer_enabled->set($old->enabled);
|
||||
$preset->wrapper->cer_bidirectional->set($old->bidirectional);
|
||||
$preset->wrapper->cer_weight->set($old->weight);
|
||||
$preset->save();
|
||||
}
|
||||
|
||||
@@ -1,39 +1,64 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Main module file.
|
||||
* Implements hook_entity_info().
|
||||
*/
|
||||
function cer_entity_info() {
|
||||
$info = array(
|
||||
'cer' => array(
|
||||
'label' => t('CER Preset'),
|
||||
'entity class' => 'CerPreset',
|
||||
'controller class' => 'CerPresetController',
|
||||
'base table' => 'cer_preset',
|
||||
'label callback' => 'entity_class_label',
|
||||
'module' => 'cer',
|
||||
'fieldable' => TRUE,
|
||||
'entity keys' => array(
|
||||
'id' => 'pid',
|
||||
'name' => 'identifier', // This is the automatically generated export key.
|
||||
'label' => 'identifier', // The identifier will be the default label.
|
||||
),
|
||||
'admin ui' => array(
|
||||
'path' => 'admin/config/content/cer',
|
||||
'file' => 'cer.admin.inc',
|
||||
'controller class' => 'CerUIController',
|
||||
),
|
||||
'exportable' => TRUE,
|
||||
'features controller class' => 'CerPresetFeaturesController',
|
||||
'access callback' => 'cer_access',
|
||||
),
|
||||
);
|
||||
|
||||
if (variable_get('cer_enable_field_ui', FALSE)) {
|
||||
$info['cer']['bundles']['cer']['admin']['path'] = $info['cer']['admin ui']['path'];
|
||||
}
|
||||
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access callback for Entity UI.
|
||||
*/
|
||||
function cer_access($op, $preset = NULL, $account = NULL) {
|
||||
return user_access('administer cer settings', $account);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_menu().
|
||||
*/
|
||||
function cer_menu() {
|
||||
$items = array();
|
||||
$info = cer_entity_info();
|
||||
$prefix = $info['cer']['admin ui']['path'];
|
||||
|
||||
$items['admin/config/system/cer'] = array(
|
||||
'title' => 'Corresponding entity references',
|
||||
'page callback' => 'drupal_get_form',
|
||||
'page arguments' => array('cer_settings_form'),
|
||||
'access arguments' => array('administer cer settings'),
|
||||
'file' => 'cer.admin.inc',
|
||||
'type' => MENU_NORMAL_ITEM,
|
||||
);
|
||||
$items['admin/config/system/cer/references'] = array(
|
||||
'title' => 'References',
|
||||
'page callback' => 'drupal_get_form',
|
||||
'page arguments' => array('cer_settings_form'),
|
||||
'access arguments' => array('administer cer settings'),
|
||||
'file' => 'cer.admin.inc',
|
||||
'type' => MENU_DEFAULT_LOCAL_TASK,
|
||||
);
|
||||
$items['admin/config/system/cer/update'] = array(
|
||||
'title' => 'Update existing entities',
|
||||
'page callback' => 'drupal_get_form',
|
||||
'page arguments' => array('cer_update_form'),
|
||||
'access arguments' => array('administer cer settings'),
|
||||
'file' => 'cer.admin.inc',
|
||||
'type' => MENU_LOCAL_TASK,
|
||||
return array(
|
||||
"{$prefix}/update" => array(
|
||||
'title' => 'Bulk Update',
|
||||
'page callback' => 'drupal_get_form',
|
||||
'page arguments' => array('cer_bulk_update_form'),
|
||||
'access arguments' => array('administer cer settings'),
|
||||
'file' => 'cer.admin.inc',
|
||||
'type' => MENU_LOCAL_TASK,
|
||||
),
|
||||
);
|
||||
|
||||
return $items;
|
||||
@@ -45,143 +70,94 @@ function cer_menu() {
|
||||
function cer_permission() {
|
||||
return array(
|
||||
'administer cer settings' => array(
|
||||
'title' => t('Administer corresponding entity reference settings'),
|
||||
'title' => t('Administer corresponding references'),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_help().
|
||||
*/
|
||||
function cer_help($path, $arg) {
|
||||
$output = '';
|
||||
if ($path == 'admin/config/system/cer') {
|
||||
$output .= t('Check which entity references should listen to each other. When checking a check box a reference on entity type A to entity B will automatically update the entity reference field on entity B adding an entry which points to entity A.');
|
||||
}
|
||||
elseif ($path == 'admin/config/system/cer/update') {
|
||||
$output .= t('This will update all the existing entities for the selected content types so that their entity reference fields are in sync.');
|
||||
$output .= '<br />';
|
||||
$output .= t('This process may take a long time depending on the number of entities you are updating.');
|
||||
$output .= '<br /><br />';
|
||||
$output .= t('When the process is finished you will see a count of the number of entities that were updated.');
|
||||
}
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_delete_instance().
|
||||
*/
|
||||
function cer_field_delete_instance($instance) {
|
||||
foreach (cer_preset_load_enabled() as $row) {
|
||||
$keys = explode('*', $row->entity_types_content_fields);
|
||||
function cer_field_delete_instance(array $instance) {
|
||||
// Delete every CER preset which refers to the deleted field instance.
|
||||
$filter = $instance['entity_type'] . ':' . $instance['bundle'] . ':' . $instance['field_name'];
|
||||
|
||||
if (($keys[0] == $instance['entity_type'] && $keys[1] == $instance['bundle'] && $keys[2] == $instance['field_name']) || ($keys[3] == $instance['entity_type'] && $keys[4] == $instance['bundle'] && $keys[5] == $instance['field_name'])) {
|
||||
cer_preset_delete($row->entity_types_content_fields);
|
||||
$baseQuery = new EntityFieldQuery();
|
||||
$baseQuery->entityCondition('entity_type', 'cer');
|
||||
$baseQuery->fieldCondition('cer_enabled', 'value', TRUE);
|
||||
|
||||
$query = clone $baseQuery;
|
||||
$query->fieldCondition('cer_left', 'path', $filter, 'CONTAINS');
|
||||
$result = $query->execute();
|
||||
if (isset($result['cer'])) {
|
||||
foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
|
||||
$preset->delete();
|
||||
}
|
||||
}
|
||||
|
||||
$query = clone $baseQuery;
|
||||
$query->fieldCondition('cer_right', 'path', $filter, 'CONTAINS');
|
||||
$result = $query->execute();
|
||||
if (isset($result['cer'])) {
|
||||
foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
|
||||
$preset->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_delete_field().
|
||||
* Implements hook_node_insert().
|
||||
*/
|
||||
function cer_field_delete_field($field) {
|
||||
foreach (cer_preset_load_enabled() as $row) {
|
||||
$keys = explode('*', $row->entity_types_content_fields);
|
||||
|
||||
if ($keys[2] == $field['field_name'] || $keys[5] == $field['field_name']) {
|
||||
cer_preset_delete($row->entity_types_content_fields);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_theme().
|
||||
*/
|
||||
function cer_theme() {
|
||||
return array(
|
||||
'cer_label' => array(
|
||||
'variables' => array('key' => ''),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function theme_cer_label($variables) {
|
||||
$key = explode(' ', $variables['key']);
|
||||
|
||||
$local = field_info_instance($key[0], $key[2], $key[1]);
|
||||
$remote = field_info_instance($key[3], $key[5], $key[4]);
|
||||
|
||||
$message = 'Correspond <span title="!local_field">%local_label</span> on !local_entity(s) of type %local_bundle with <span title="!remote_field">%remote_label</span> on !remote_entity(s) of type %remote_bundle.';
|
||||
|
||||
$variables = array(
|
||||
'%local_label' => $local['label'],
|
||||
'!local_field' => $local['field_name'],
|
||||
'!local_entity' => $local['entity_type'],
|
||||
'%local_bundle' => $local['bundle'],
|
||||
'%remote_label' => $remote['label'],
|
||||
'!remote_field' => $remote['field_name'],
|
||||
'!remote_entity' => $remote['entity_type'],
|
||||
'%remote_bundle' => $remote['bundle'],
|
||||
);
|
||||
|
||||
return t($message, $variables);
|
||||
function cer_node_insert(StdClass $node) {
|
||||
// Write access grants *before* doing CER stuff in order to prevent a race condition.
|
||||
// This tricky bug can easily rear its ugly head if you have an Entity Reference field,
|
||||
// referencing nodes, and a node access module enabled.
|
||||
//
|
||||
// Entity Reference's bundled selection handlers will use either EntityFieldQuery or
|
||||
// Views, both of which are affected by node access grants (and rightfully so).
|
||||
// However, when creating a node, core invokes hook_node_save() *before* it writes the
|
||||
// grants to the database, which can cause EntityFieldQuery (or Views, unless
|
||||
// configured to disable SQL rewriting) to return no results if the user isn't the
|
||||
// superuser. Since CER asks the field backend to validate the reference, this can
|
||||
// cause the reference to not be validated, and the cross-reference to fail.
|
||||
//
|
||||
// Really, this is a core issue and not a CER issue. Core should be invoking
|
||||
// hook_node_save() AFTER it writes access info. But we can work around it by writing
|
||||
// the access info, doing our own processing, and then clearing the access info
|
||||
// so node_save() can write it cleanly. And that's what this does.
|
||||
//
|
||||
// Hear that, core devs? Fix it fix it fix it!
|
||||
//
|
||||
node_access_acquire_grants($node);
|
||||
cer_processing_entity('insert', $node, 'node');
|
||||
db_delete('node_access')->condition('nid', $node->nid)->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_insert().
|
||||
*/
|
||||
function cer_entity_insert($entity, $type) {
|
||||
cer_processing_entity('insert', $entity, $type);
|
||||
if (! function_exists("cer_{$type}_insert")) {
|
||||
cer_processing_entity('insert', $entity, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_update().
|
||||
*/
|
||||
function cer_entity_update($entity, $type) {
|
||||
cer_processing_entity('update', $entity, $type);
|
||||
if (! function_exists("cer_{$type}_update")) {
|
||||
cer_processing_entity('update', $entity, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_delete().
|
||||
*/
|
||||
function cer_entity_delete($entity, $type) {
|
||||
cer_processing_entity('delete', $entity, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load enabled CER presets.
|
||||
*/
|
||||
function cer_preset_load_enabled() {
|
||||
ctools_include('export');
|
||||
return ctools_export_load_object('cer', 'conditions', array('enabled' => 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return CER preset by key.
|
||||
*/
|
||||
function cer_preset_load($key) {
|
||||
ctools_include('export');
|
||||
return ctools_export_crud_load('cer', $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return 1 if CER preset specified by given key is enabled.
|
||||
*/
|
||||
function cer_preset_enabled($key) {
|
||||
$preset = cer_preset_load($key);
|
||||
return empty($preset) ? 0 : $preset->enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes or disables a given CER preset.
|
||||
*/
|
||||
function cer_preset_delete($key) {
|
||||
ctools_include('export');
|
||||
|
||||
ctools_export_crud_delete('cer', $key);
|
||||
ctools_export_crud_disable('cer', $key);
|
||||
|
||||
ctools_export_load_object_reset('cer');
|
||||
if (! function_exists("cer_{$type}_delete")) {
|
||||
cer_processing_entity('delete', $entity, $type);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -191,65 +167,73 @@ function cer_preset_delete($key) {
|
||||
* The operation being performed on the entity (insert, update, or delete).
|
||||
*
|
||||
* @param object $entity
|
||||
* The entity or the entity's id.
|
||||
* The entity object (optionally wrapped), or its ID.
|
||||
*
|
||||
* @param string $entity_type
|
||||
* The entity type.
|
||||
* The entity type. If $entity is wrapped, this can be NULL since the entity
|
||||
* type is known by the wrapper.
|
||||
*
|
||||
* @param array $context
|
||||
* Either the Batch API context (since this is the callback function used
|
||||
* during bulk update) or NULL if we're not in a batch job.
|
||||
*/
|
||||
function cer_processing_entity($op, $entity, $entity_type, &$context = NULL) {
|
||||
// Load the entity if we're given an ID rather than an entity.
|
||||
if (!is_object($entity)) {
|
||||
$entity = entity_load($entity_type, array($entity));
|
||||
$entity = reset($entity);
|
||||
function cer_processing_entity($op, $entity, $entity_type = NULL, array &$context = NULL) {
|
||||
// Don't do anything if the MAINTENANCE_MODE flag is set. This isn't the same thing
|
||||
// as user-facing maintenance mode, but rather is set when running, say, update.php
|
||||
// or another relatively low-level operation. This was added to prevent CER from
|
||||
// running while updating from 1.x or 2.x, since classes may not yet be registered
|
||||
// yet and we don't want to cause fatal errors during update.
|
||||
if (defined('MAINTENANCE_MODE')) {
|
||||
return;
|
||||
}
|
||||
// If the entity is of the wrong type, entity_extract_IDs() will throw
|
||||
// EntityMalformedException and rightfully bail out here.
|
||||
list (, , $bundle) = entity_extract_IDs($entity_type, $entity);
|
||||
|
||||
$result = cer_preset_load_enabled();
|
||||
|
||||
foreach ($result as $row) {
|
||||
$keys = explode('*', $row->entity_types_content_fields);
|
||||
|
||||
if ($keys[0] == $entity_type && $keys[1] == $bundle) {
|
||||
try {
|
||||
$handler = new CerHandler($row->entity_types_content_fields, $entity);
|
||||
call_user_func(array($handler, $op));
|
||||
}
|
||||
catch (CerException $e) {
|
||||
if (isset($context)) {
|
||||
$context['results']['errors'][] = $e;
|
||||
}
|
||||
else {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
// Don't process anything that hasn't got the cer data structure: this provides an
|
||||
// opportunity for other modules to opt their entities out of CER processing.
|
||||
if ($entity instanceof EntityStructureWrapper) {
|
||||
try {
|
||||
// If there is no such a property an exception will be thrown.
|
||||
$entity->getPropertyInfo('cer');
|
||||
}
|
||||
|
||||
if ($keys[3] == $entity_type && $keys[4] == $bundle) {
|
||||
$preset = implode('*', array($keys[3], $keys[4], $keys[5], $keys[0], $keys[1], $keys[2]));
|
||||
|
||||
try {
|
||||
$handler = new CerHandler($preset, $entity);
|
||||
call_user_func(array($handler, $op));
|
||||
}
|
||||
catch (CerException $e) {
|
||||
if (isset($context)) {
|
||||
$context['results']['errors'][] = $e;
|
||||
}
|
||||
else {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
catch (EntityMetadataWrapperException $e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($context)) {
|
||||
$context['results']['count']++;
|
||||
if ($entity instanceof EntityDrupalWrapper) {
|
||||
// Under certain circumstances, the cer struct may not be known to Entity
|
||||
// API. So check for that before doing any actual processing. If it's not
|
||||
// known yet, rebuild the property info cache and re-instantiate the
|
||||
// wrapper with all the latest property definitions.
|
||||
try {
|
||||
$entity->getPropertyInfo('cer');
|
||||
}
|
||||
catch (EntityMetadataWrapperException $e) {
|
||||
entity_property_info_cache_clear();
|
||||
$entity = new EntityDrupalWrapper($entity->type(), $entity->value());
|
||||
}
|
||||
|
||||
$finder = new CerPresetFinder($entity);
|
||||
|
||||
foreach ($finder->execute() as $preset) {
|
||||
$handler = new CerPresetHandler($preset, $entity);
|
||||
$handler->$op();
|
||||
}
|
||||
|
||||
if ($context) {
|
||||
if (! isset($context['results']['count'])) {
|
||||
$context['results']['count'] = 0;
|
||||
}
|
||||
$context['results']['count']++;
|
||||
}
|
||||
}
|
||||
elseif ($entity_type) {
|
||||
if (is_numeric($entity)) {
|
||||
$entity = entity_object_load($entity, $entity_type);
|
||||
}
|
||||
|
||||
if (is_object($entity) && empty($entity->cer_processed)) {
|
||||
cer_processing_entity($op, new EntityDrupalWrapper($entity_type, $entity), NULL, $context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,39 +264,155 @@ function cer_batch_update_existing_finished($success, $results, $operations) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_ctools_plugin_api().
|
||||
* Implements hook_hook_info().
|
||||
*
|
||||
* @see cer.api.php for info about what these hooks do.
|
||||
*/
|
||||
function cer_ctools_plugin_api($owner, $api) {
|
||||
if ($owner == 'cer' && $api == 'default_cer_presets') {
|
||||
return array('version' => 1);
|
||||
}
|
||||
function cer_hook_info() {
|
||||
return array(
|
||||
'cer_fields' => array(
|
||||
'group' => 'cer',
|
||||
),
|
||||
'cer_fields_alter' => array(
|
||||
'group' => 'cer',
|
||||
),
|
||||
// This is not used except when rebuilding legacy presets. It's here to
|
||||
// ensure that MODULE.cer.inc is auto-loaded when loading legacy presets
|
||||
// from code. (@see cer_update_7005())
|
||||
'cer_default_presets' => array(
|
||||
'group' => 'cer',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update field data.
|
||||
*
|
||||
* @param $node the referenced node to be updated.
|
||||
* Returns options for the cer_weight field.
|
||||
*/
|
||||
function _cer_update($entity_type, $entity) {
|
||||
$entity->original = isset($entity->original) ? $entity->original : NULL;
|
||||
function cer_weight_options() {
|
||||
$options = array();
|
||||
|
||||
$extract_ids = entity_extract_IDs($entity_type, $entity);
|
||||
$id = array_shift($extract_ids);
|
||||
|
||||
field_attach_presave($entity_type, $entity);
|
||||
field_attach_update($entity_type, $entity);
|
||||
|
||||
// Issue #2212499.
|
||||
if ($entity_type == 'node') {
|
||||
$entity->changed = time();
|
||||
|
||||
db_update('node')
|
||||
->fields(array(
|
||||
'changed' => $entity->changed,
|
||||
))
|
||||
->condition('nid', $id)
|
||||
->execute();
|
||||
for ($i = -50; $i <= 50; $i++) {
|
||||
$options[$i] = $i;
|
||||
}
|
||||
|
||||
entity_get_controller($entity_type)->resetCache(array($id));
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_features_ignore().
|
||||
*/
|
||||
function cer_features_ignore($component) {
|
||||
$ignores = array();
|
||||
if ($component == 'cer') {
|
||||
$ignores['wrapper'] = 0;
|
||||
}
|
||||
return $ignores;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_features_override_ignore().
|
||||
*/
|
||||
function cer_features_override_ignore($component) {
|
||||
return cer_features_ignore($component);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_property_info().
|
||||
*/
|
||||
function cer_entity_property_info() {
|
||||
$properties = array();
|
||||
|
||||
foreach (entity_get_info() as $entity_type => $entity_info) {
|
||||
// Expose a 'cer' struct on every entity type so that we can get special
|
||||
// entity-specific information during processing. This stuff is wrapped in
|
||||
// a struct to avoid namespace collisions, which can be disastrous.
|
||||
//
|
||||
// @see Issue #2223467
|
||||
//
|
||||
$properties[$entity_type]['properties']['cer'] = array(
|
||||
'label' => t('CER'),
|
||||
'description' => t('Information about the entity, used internally by CER.'),
|
||||
'type' => 'struct',
|
||||
'getter callback' => 'cer_get_cer_struct',
|
||||
'computed' => TRUE,
|
||||
'property info' => array(
|
||||
// lineage is a chain string, in the format used by {cer}.a and {cer}.b.
|
||||
// e.g., node:article:field_related_pages.
|
||||
'lineage' => array(
|
||||
'label' => t('Context'),
|
||||
'description' => t("The entity's lineage, represented as a string."),
|
||||
'type' => 'text',
|
||||
'getter callback' => 'cer_get_entity_lineage',
|
||||
'computed' => TRUE,
|
||||
),
|
||||
// The depth of the entity. The default callback will just return 1, since most
|
||||
// entities don't live inside other entities (field collections are the main
|
||||
// exception).
|
||||
'depth' => array(
|
||||
'label' => t('Depth'),
|
||||
'description' => t("How deeply the entity is embedded."),
|
||||
'type' => 'integer',
|
||||
'getter callback' => 'cer_get_entity_depth',
|
||||
'computed' => TRUE,
|
||||
),
|
||||
// The default callback returns the original entity because, as with the depth
|
||||
// property, most entities don't live inside other entities.
|
||||
'owner' => array(
|
||||
'label' => t('Owner'),
|
||||
'description' => t('The top-level entity under which this one is embedded.'),
|
||||
'type' => 'entity',
|
||||
'getter callback' => 'cer_get_entity_owner',
|
||||
'computed' => TRUE,
|
||||
),
|
||||
// A wrapper around $entity->original that returns the current entity if there is
|
||||
// no original version available (i.e., during bulk update).
|
||||
'original' => array(
|
||||
'label' => t('Original'),
|
||||
'description' => t('The original entity (before update), or the current entity if an update has not occurred.'),
|
||||
'type' => 'entity',
|
||||
'getter callback' => 'cer_get_entity_original',
|
||||
'computed' => TRUE,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return $properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_property_info_alter().
|
||||
*/
|
||||
function cer_entity_property_info_alter(array &$info) {
|
||||
// Add a 'chain' property to the cer_left and cer_right fields so we can
|
||||
// easily get the field's value represented as a CerFieldChain.
|
||||
$info['cer']['bundles']['cer']['properties']['cer_left']['property info'] =
|
||||
$info['cer']['bundles']['cer']['properties']['cer_right']['property info'] = array(
|
||||
'chain' => array(
|
||||
'label' => t('Chain'),
|
||||
'description' => t('A CER field chain to the field instance.'),
|
||||
'type' => 'struct',
|
||||
'getter callback' => 'cer_unpack_field_chain',
|
||||
'computed' => TRUE,
|
||||
),
|
||||
);
|
||||
|
||||
// Field collections are special. Because they live inside other entities (to
|
||||
// potentially infinite levels of recursion), their CER property callbacks must be
|
||||
// able to recurse upwards through the chain of embedding.
|
||||
if (module_exists('field_collection')) {
|
||||
$struct = &$info['field_collection_item']['properties']['cer']['property info'];
|
||||
|
||||
$struct['lineage']['getter callback'] = 'cer_get_field_collection_lineage';
|
||||
$struct['lineage']['raw getter callback'] = 'cer_get_field_collection_lineage_array';
|
||||
$struct['depth']['getter callback'] = 'cer_get_field_collection_depth';
|
||||
$struct['owner']['getter callback'] = 'cer_get_field_collection_owner';
|
||||
}
|
||||
}
|
||||
|
||||
// Include property callback functions
|
||||
module_load_include('inc', 'cer', 'cer.properties');
|
||||
|
||||
if (module_exists('field_collection')) {
|
||||
module_load_include('inc', 'cer', 'cer.properties.field_collection');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains entity property callback functions for the 'cer' struct exposed
|
||||
* to Entity API on field collections.
|
||||
*
|
||||
* @see cer_entity_property_info_alter().
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets a field collection's lineage as a string, e.g.
|
||||
* node:page:field_my_collection::field_collection_item:field_my_collection:%
|
||||
*/
|
||||
function cer_get_field_collection_lineage(array $data, array $options, $property, $data_type, array $info) {
|
||||
return implode('::', $info['raw getter callback']($data, $options, $property, $data_type, $info));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a field collection's lineage as an array.
|
||||
*/
|
||||
function cer_get_field_collection_lineage_array(array $data, array $options, $property, $data_type, array $info) {
|
||||
$collection = $data[1];
|
||||
|
||||
// If this is the innermost entity, $options['lineage'] will be empty.
|
||||
if (! isset($options['lineage'])) {
|
||||
$options['lineage'][] = "field_collection_item:{$collection->field_name}:";
|
||||
}
|
||||
|
||||
$data[0] = $collection->hostEntityType();
|
||||
$data[1] = $collection->hostEntity();
|
||||
list (, , $host_bundle) = entity_extract_IDs($data[0], $data[1]);
|
||||
array_unshift($options['lineage'], $data[0] . ":{$host_bundle}:{$collection->field_name}");
|
||||
|
||||
// If this field collection is hosted in another field collection, recurse
|
||||
// upward. Otherwise, we're done; return the lineage array.
|
||||
if ($data[0] == 'field_collection_item') {
|
||||
return cer_get_field_collection_lineage_array($data, $options, $property, $data_type, $info);
|
||||
}
|
||||
else {
|
||||
return $options['lineage'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the zero-based depth of a field collection.
|
||||
*/
|
||||
function cer_get_field_collection_depth(array $data, array $options, $property, $data_type, array $info) {
|
||||
$lineage = cer_get_field_collection_lineage_array($data, $options, $property, $data_type, $info);
|
||||
return (sizeof($lineage) - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ultimate owner of a field collection -- that is, the top-level entity
|
||||
* under which it's embedded. This could be any kind of entity that's not a field
|
||||
* collection item.
|
||||
*/
|
||||
function cer_get_field_collection_owner(array $data, array $options, $property, $data_type, array $info) {
|
||||
// If the entity is a field collection item, recurse upward. Otherwise,
|
||||
// return the wrapped entity.
|
||||
if ($data[0] == 'field_collection_item') {
|
||||
$data[0] = $data[1]->hostEntityType();
|
||||
$data[1] = $data[1]->hostEntity();
|
||||
|
||||
$self = __FUNCTION__;
|
||||
return $self($data, $options, $property, $data_type, $info);
|
||||
}
|
||||
else {
|
||||
return new EntityDrupalWrapper($data[0], $data[1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains entity property callback functions for the 'cer' struct exposed
|
||||
* to Entity API.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Unpacks the cer_left and cer_right values into a CerFieldChain object.
|
||||
*/
|
||||
function cer_unpack_field_chain($data, array $options, $property, $entity_type, array $info) {
|
||||
return CerFieldChain::unpack($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a parent struct for the lineage, depth, owner, and original properties.
|
||||
* All that these other callbacks really need is the entity type and object, so
|
||||
* that's what this returns.
|
||||
*/
|
||||
function cer_get_cer_struct($entity, array $options, $property, $entity_type, array $info) {
|
||||
return array( $entity_type, $entity );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the lineage of the entity as a string, in the format entity_type:bundle:%
|
||||
*/
|
||||
function cer_get_entity_lineage(array $data, array $options, $property, $data_type, array $info) {
|
||||
list (, , $bundle) = entity_extract_IDs($data[0], $data[1]);
|
||||
return $data[0] . ":{$bundle}:";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the entity depth as an integer. cer_entity_property_info_alter() overrides this
|
||||
* callback for field collections, and for all other entity types it's 0 (top level).
|
||||
*/
|
||||
function cer_get_entity_depth(array $data, array $options, $property, $data_type, array $info) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ultimate owner of the entity as an EntityDrupalWrapper. cer_entity_property_info_alter()
|
||||
* overrides this callback for field collections, and for all other entity types the entity
|
||||
* owns itself.
|
||||
*/
|
||||
function cer_get_entity_owner(array $data, array $options, $property, $data_type, array $info) {
|
||||
return new EntityDrupalWrapper($data[0], $data[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the original entity, before update. If no update has taken place, the current
|
||||
* entity is returned.
|
||||
*/
|
||||
function cer_get_entity_original(array $data, array $options, $property, $data_type, array $info) {
|
||||
return new EntityDrupalWrapper($data[0], (isset($data[1]->original) ? $data[1]->original : $data[1]));
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_cer_fields().
|
||||
*/
|
||||
function cer_commerce_cer_fields() {
|
||||
module_load_include('inc', 'cer', 'cer.cer');
|
||||
return _cer_collect_fields_of_type('commerce_product_reference', 'CerCommerceProductReferenceField');
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
name = "CER Commerce"
|
||||
core = "7.x"
|
||||
description = "Provides a CER plugin for Commerce's Product Reference fields."
|
||||
dependencies[] = cer
|
||||
dependencies[] = commerce_product_reference
|
||||
|
||||
files[] = commerce_product_reference.inc
|
||||
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1455299962"
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_cer_insert().
|
||||
*/
|
||||
function cer_commerce_cer_insert(CerPreset $preset) {
|
||||
// Prevents a race condition when deleting Commerce products which are referred to
|
||||
// by Product Reference fields managed by CER.
|
||||
if ($preset->wrapper->cer_right->chain->value()->end() instanceof CerCommerceProductReferenceField) {
|
||||
$preset->wrapper->cer_bidirectional->set(FALSE);
|
||||
$preset->save();
|
||||
|
||||
drupal_set_message(t('In order to prevent a race condition, bidirectionality has been disabled for this preset.'), 'warning');
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains a CER plugin for Commerce's Product Reference fields.
|
||||
*/
|
||||
|
||||
class CerCommerceProductReferenceField extends CerField {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return 'commerce_product';
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
// Product reference fields store their referenceable types by instance
|
||||
// instead of by field, so the $this->settings variable we inherit
|
||||
// from CerField is useless here.
|
||||
$instance = field_info_instance($this->entityType, $this->name, $this->bundle);
|
||||
$types = $instance['settings']['referenceable_types'];
|
||||
|
||||
return ($types ? $types : parent::getTargetBundles());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
name = "CER Entity Settings"
|
||||
core = "7.x"
|
||||
description = "Allows administrators and content authors to override CER settings for individual entities."
|
||||
|
||||
dependencies[] = cer
|
||||
dependencies[] = entityreference
|
||||
dependencies[] = views
|
||||
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1455299962"
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_install().
|
||||
*/
|
||||
function cer_entity_settings_install() {
|
||||
$fields = array();
|
||||
|
||||
$fields[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => FIELD_CARDINALITY_UNLIMITED,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_settings',
|
||||
'foreign keys' => array(
|
||||
'cer_preset' => array(
|
||||
'columns' => array(
|
||||
'target_id' => 'pid',
|
||||
),
|
||||
'table' => 'cer_preset',
|
||||
),
|
||||
),
|
||||
'indexes' => array(
|
||||
'target_id' => array(
|
||||
0 => 'target_id',
|
||||
),
|
||||
),
|
||||
'locked' => TRUE,
|
||||
'module' => 'entityreference',
|
||||
'settings' => array(
|
||||
// This field uses a simple custom selection handler that selects CER
|
||||
// presets which apply to the given entity.
|
||||
'handler' => 'cer',
|
||||
'handler_settings' => array(
|
||||
'behaviors' => array(
|
||||
'views-select-list' => array(
|
||||
'status' => 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
'target_type' => 'cer',
|
||||
),
|
||||
'translatable' => 0,
|
||||
'type' => 'entityreference',
|
||||
);
|
||||
|
||||
$fields[] = array(
|
||||
'active' => 1,
|
||||
'cardinality' => 1,
|
||||
'deleted' => 0,
|
||||
'entity_types' => array(),
|
||||
'field_name' => 'cer_store_settings',
|
||||
'foreign keys' => array(),
|
||||
'indexes' => array(
|
||||
'value' => array(
|
||||
0 => 'value',
|
||||
),
|
||||
),
|
||||
'locked' => TRUE,
|
||||
'module' => 'list',
|
||||
'settings' => array(
|
||||
'allowed_values' => array(
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
),
|
||||
'allowed_values_function' => '',
|
||||
),
|
||||
'translatable' => 0,
|
||||
'type' => 'list_boolean',
|
||||
);
|
||||
|
||||
array_walk($fields, 'field_create_field');
|
||||
|
||||
$query = new EntityFieldQuery();
|
||||
$result = $query->entityCondition('entity_type', 'cer')->execute();
|
||||
if (isset($result['cer'])) {
|
||||
foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
|
||||
cer_entity_settings_cer_update($preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_uninstall().
|
||||
*/
|
||||
function cer_entity_settings_uninstall() {
|
||||
field_delete_field('cer_settings');
|
||||
field_delete_field('cer_store_settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_update_dependencies().
|
||||
*/
|
||||
function cer_entity_settings_update_dependencies() {
|
||||
return array(
|
||||
'cer_entity_settings' => array(
|
||||
7001 => array(
|
||||
'cer' => 7005,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the cer_entity_settings database table.
|
||||
*/
|
||||
function cer_entity_settings_update_7001() {
|
||||
db_drop_table('cer_entity_settings');
|
||||
cer_entity_settings_install();
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_views_api().
|
||||
*/
|
||||
function cer_entity_settings_views_api() {
|
||||
return array('api' => 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_query_TAG_alter().
|
||||
*/
|
||||
function cer_entity_settings_query_cer_presets_alter(QueryAlterableInterface $query) {
|
||||
$entity = $query->getMetaData('entity');
|
||||
|
||||
$instance = field_info_instance($entity->type(), 'cer_settings', $entity->getBundle());
|
||||
if ($instance) {
|
||||
$IDs = array();
|
||||
|
||||
foreach ($entity->cer_settings as $preset) {
|
||||
$IDs[] = $preset->getIdentifier();
|
||||
}
|
||||
|
||||
// If no presets were selected, guarantee an empty result set by selecting
|
||||
// the non-existent preset ID 0.
|
||||
if (empty($IDs)) {
|
||||
$IDs[] = 0;
|
||||
}
|
||||
$query->getMetaData('entity_field_query')->entityCondition('entity_id', $IDs, 'IN');
|
||||
|
||||
if (! $entity->cer_store_settings->value()) {
|
||||
$queue = &drupal_static('cer_entity_settings_exit', array());
|
||||
$queue[ $entity->type() ][ $entity->getIdentifier() ] = $entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_exit().
|
||||
*/
|
||||
function cer_entity_settings_exit() {
|
||||
$queue = drupal_static(__FUNCTION__, array());
|
||||
|
||||
foreach ($queue as $entity_type => $entities) {
|
||||
foreach ($entities as $entity) {
|
||||
// Clear out the stored settings.
|
||||
$entity->cer_settings->set(NULL);
|
||||
|
||||
$entity = $entity->value();
|
||||
$entity->cer_processed = TRUE;
|
||||
entity_save($entity_type, $entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_cron().
|
||||
*/
|
||||
function cer_entity_settings_cron($field = NULL) {
|
||||
// Delete defunct instances of the given field. An instance is considered
|
||||
// defunct if there are no presets which refer the entity type and bundle
|
||||
// on which it's instantiated.
|
||||
if (isset($field)) {
|
||||
$view = views_get_view('cer_endpoint_in_use');
|
||||
|
||||
$field = field_info_field($field);
|
||||
|
||||
// Loop through every instance of the field, executing the view for each one.
|
||||
foreach ($field['bundles'] as $entity_type => $bundles) {
|
||||
foreach ($bundles as $bundle) {
|
||||
$view->set_exposed_input(array(
|
||||
'left' => "{$entity_type}:{$bundle}:",
|
||||
'right' => "{$entity_type}:{$bundle}:",
|
||||
));
|
||||
$view->execute();
|
||||
|
||||
if (empty($view->result)) {
|
||||
$instance = field_info_instance($entity_type, $field['field_name'], $bundle);
|
||||
|
||||
if ($instance) {
|
||||
// Do NOT delete the field if this is the last instance of it. We
|
||||
// clean up our own fields during uninstall.
|
||||
field_delete_instance($instance, FALSE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
call_user_func(__FUNCTION__, 'cer_settings');
|
||||
call_user_func(__FUNCTION__, 'cer_store_settings');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_ctools_plugin_directory().
|
||||
*/
|
||||
function cer_entity_settings_ctools_plugin_directory($owner, $plugin_type) {
|
||||
return "plugins/{$owner}/{$plugin_type}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_cer_insert().
|
||||
*/
|
||||
function cer_entity_settings_cer_insert(CerPreset $preset) {
|
||||
cer_entity_settings_cer_update($preset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_cer_update().
|
||||
*/
|
||||
function cer_entity_settings_cer_update(CerPreset $preset) {
|
||||
_cer_entity_settings_create_instance($preset->wrapper->cer_left->chain->value());
|
||||
_cer_entity_settings_create_instance($preset->wrapper->cer_right->chain->value());
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates the cer_settings and cer_store_settings fields at the head of
|
||||
* the given chain, if they aren't already there.
|
||||
*/
|
||||
function _cer_entity_settings_create_instance(FieldChain $chain) {
|
||||
$field = $chain->current();
|
||||
|
||||
$instance = field_info_instance($field->entityType, 'cer_settings', $field->bundle);
|
||||
if (empty($instance)) {
|
||||
$instance = array(
|
||||
'bundle' => $field->bundle,
|
||||
'default_value' => NULL,
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'above',
|
||||
'module' => 'entityreference',
|
||||
'settings' => array(
|
||||
'link' => FALSE,
|
||||
),
|
||||
'type' => 'entityreference_label',
|
||||
'weight' => 1,
|
||||
),
|
||||
),
|
||||
'entity_type' => $field->entityType,
|
||||
'field_name' => 'cer_settings',
|
||||
'label' => t('Synchronize this @entity_type with...', array(
|
||||
'@entity_type' => $field->entityTypeLabel,
|
||||
)),
|
||||
'required' => 0,
|
||||
'settings' => array(
|
||||
),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(
|
||||
'match_operator' => 'CONTAINS',
|
||||
'path' => '',
|
||||
'size' => 60,
|
||||
),
|
||||
'type' => 'options_buttons',
|
||||
'weight' => 1,
|
||||
),
|
||||
);
|
||||
field_create_instance($instance);
|
||||
}
|
||||
|
||||
$instance = field_info_instance($field->entityType, 'cer_store_settings', $field->bundle);
|
||||
if (empty($instance)) {
|
||||
$instance = array(
|
||||
'bundle' => $field->bundle,
|
||||
'default_value' => array(
|
||||
0 => array(
|
||||
'value' => 1,
|
||||
),
|
||||
),
|
||||
'deleted' => 0,
|
||||
'description' => '',
|
||||
'display' => array(
|
||||
'default' => array(
|
||||
'label' => 'above',
|
||||
'module' => 'list',
|
||||
'settings' => array(),
|
||||
'type' => 'list_default',
|
||||
'weight' => 2,
|
||||
),
|
||||
'teaser' => array(
|
||||
'label' => 'above',
|
||||
'settings' => array(),
|
||||
'type' => 'hidden',
|
||||
'weight' => 0,
|
||||
),
|
||||
),
|
||||
'entity_type' => $field->entityType,
|
||||
'field_name' => 'cer_store_settings',
|
||||
'label' => t('Remember these settings'),
|
||||
'required' => 0,
|
||||
'settings' => array(
|
||||
),
|
||||
'widget' => array(
|
||||
'active' => 1,
|
||||
'module' => 'options',
|
||||
'settings' => array(
|
||||
'display_label' => 1,
|
||||
),
|
||||
'type' => 'options_onoff',
|
||||
'weight' => 2,
|
||||
),
|
||||
);
|
||||
field_create_instance($instance);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_views_default_views().
|
||||
*/
|
||||
function cer_entity_settings_views_default_views() {
|
||||
$views = array();
|
||||
|
||||
$view = new view();
|
||||
$view->name = 'cer_endpoint_in_use';
|
||||
$view->description = '';
|
||||
$view->tag = 'CER Entity Settings';
|
||||
$view->base_table = 'cer_preset';
|
||||
$view->human_name = 'CER Endpoints in Use';
|
||||
$view->core = 7;
|
||||
$view->api_version = '3.0';
|
||||
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
|
||||
|
||||
/* Display: Master */
|
||||
$handler = $view->new_display('default', 'Master', 'default');
|
||||
$handler->display->display_options['use_more_always'] = FALSE;
|
||||
$handler->display->display_options['access']['type'] = 'none';
|
||||
$handler->display->display_options['cache']['type'] = 'none';
|
||||
$handler->display->display_options['query']['type'] = 'views_query';
|
||||
$handler->display->display_options['exposed_form']['type'] = 'basic';
|
||||
$handler->display->display_options['pager']['type'] = 'none';
|
||||
$handler->display->display_options['pager']['options']['offset'] = '0';
|
||||
$handler->display->display_options['style_plugin'] = 'default';
|
||||
$handler->display->display_options['row_plugin'] = 'entity';
|
||||
$handler->display->display_options['row_options']['view_mode'] = 'default';
|
||||
$handler->display->display_options['filter_groups']['groups'] = array(
|
||||
1 => 'OR',
|
||||
);
|
||||
/* Filter criterion: CER Preset: Left Field (cer_left) */
|
||||
$handler->display->display_options['filters']['cer_left_path']['id'] = 'cer_left_path';
|
||||
$handler->display->display_options['filters']['cer_left_path']['table'] = 'field_data_cer_left';
|
||||
$handler->display->display_options['filters']['cer_left_path']['field'] = 'cer_left_path';
|
||||
$handler->display->display_options['filters']['cer_left_path']['operator'] = 'starts';
|
||||
$handler->display->display_options['filters']['cer_left_path']['group'] = 1;
|
||||
$handler->display->display_options['filters']['cer_left_path']['exposed'] = TRUE;
|
||||
$handler->display->display_options['filters']['cer_left_path']['expose']['operator_id'] = 'cer_left_path_op';
|
||||
$handler->display->display_options['filters']['cer_left_path']['expose']['label'] = 'Left Field';
|
||||
$handler->display->display_options['filters']['cer_left_path']['expose']['operator'] = 'cer_left_path_op';
|
||||
$handler->display->display_options['filters']['cer_left_path']['expose']['identifier'] = 'left';
|
||||
$handler->display->display_options['filters']['cer_left_path']['expose']['remember_roles'] = array(
|
||||
2 => '2',
|
||||
1 => 0,
|
||||
);
|
||||
/* Filter criterion: CER Preset: Right Field (cer_right) */
|
||||
$handler->display->display_options['filters']['cer_right_path']['id'] = 'cer_right_path';
|
||||
$handler->display->display_options['filters']['cer_right_path']['table'] = 'field_data_cer_right';
|
||||
$handler->display->display_options['filters']['cer_right_path']['field'] = 'cer_right_path';
|
||||
$handler->display->display_options['filters']['cer_right_path']['operator'] = 'starts';
|
||||
$handler->display->display_options['filters']['cer_right_path']['group'] = 1;
|
||||
$handler->display->display_options['filters']['cer_right_path']['exposed'] = TRUE;
|
||||
$handler->display->display_options['filters']['cer_right_path']['expose']['operator_id'] = 'cer_right_path_op';
|
||||
$handler->display->display_options['filters']['cer_right_path']['expose']['label'] = 'Right Field';
|
||||
$handler->display->display_options['filters']['cer_right_path']['expose']['operator'] = 'cer_right_path_op';
|
||||
$handler->display->display_options['filters']['cer_right_path']['expose']['identifier'] = 'right';
|
||||
$handler->display->display_options['filters']['cer_right_path']['expose']['remember_roles'] = array(
|
||||
2 => '2',
|
||||
1 => 0,
|
||||
);
|
||||
$views[$view->name] = $view;
|
||||
|
||||
return $views;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
class CerPresetSelectionHandler implements EntityReference_SelectionHandler {
|
||||
|
||||
private $entity;
|
||||
|
||||
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
|
||||
return new CerPresetSelectionHandler($entity_type, $entity);
|
||||
}
|
||||
|
||||
public function __construct($entity_type, $entity) {
|
||||
if ($entity_type && $entity) {
|
||||
$this->entity = new EntityDrupalWrapper($entity_type, $entity);
|
||||
}
|
||||
}
|
||||
|
||||
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
|
||||
$options = array();
|
||||
|
||||
if ($this->entity) {
|
||||
$finder = new CerPresetFinder($this->entity);
|
||||
$finder->execute();
|
||||
|
||||
foreach ($finder->result['cer'] as $preset) {
|
||||
$options['cer'][$preset->pid] = $preset->label_variables['@right'];
|
||||
}
|
||||
|
||||
foreach ($finder->result['cer__invert'] as $preset) {
|
||||
$options['cer'][$preset->pid] = $preset->label_variables['@left'];
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
|
||||
return sizeof($this->getReferencableEntities());
|
||||
}
|
||||
|
||||
public function validateReferencableEntities(array $IDs) {
|
||||
// Don't bother validating preset IDs.
|
||||
return $IDs;
|
||||
}
|
||||
|
||||
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
public function entityFieldQueryAlter(SelectQueryInterface $query) {
|
||||
// NOP
|
||||
}
|
||||
|
||||
public function getLabel($entity) {
|
||||
return entity_label('cer', $entity);
|
||||
}
|
||||
|
||||
public static function settingsForm($field, $instance) {
|
||||
return array();
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
$plugin = array(
|
||||
'title' => t('CER Presets'),
|
||||
'class' => 'CerPresetSelectionHandler',
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
name = "CER Inline Entity Form"
|
||||
core = "7.x"
|
||||
description = "Provides an option to hide CER fields on Inline Entity Forms."
|
||||
dependencies[] = cer
|
||||
dependencies[] = inline_entity_form
|
||||
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1455299962"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Provides an option to hide CER fields on inline entity forms. Spun off
|
||||
* from Issue #2240371.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implements hook_form_FORM_ID_alter().
|
||||
*/
|
||||
function cer_ief_form_field_ui_field_edit_form_alter(array &$form, array &$form_state) {
|
||||
// Add options to hide corresponding entity reference fields on inline entity forms.
|
||||
$instance = $form['#instance'];
|
||||
if ($instance['widget']['type'] == 'inline_entity_form') {
|
||||
// Build a filter to fetch matching CER presets for this field instance.
|
||||
$entity_type = $instance['entity_type'];
|
||||
$bundle = $instance['bundle'];
|
||||
$field_name = $instance['field_name'];
|
||||
$filter = "{$entity_type}:{$bundle}:{$field_name}";
|
||||
|
||||
if ($presets = _cer_filter_presets($filter)) {
|
||||
// There are available CER configurations for this IEF instance.
|
||||
// Add option to hide field(s) on referenced entities.
|
||||
$ief_settings = &$form['instance']['widget']['settings']['type_settings'];
|
||||
$ief_settings['hide_cer_fields'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Hide corresponding entity reference field(s) on form.'),
|
||||
'#default_value' => !empty($instance['widget']['settings']['type_settings']['hide_cer_fields']),
|
||||
);
|
||||
// @todo Add checkbox for each corresponding field?
|
||||
// foreach ($presets as $preset) etc.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_widget_form_alter().
|
||||
*
|
||||
* @todo This could be cached into an array and only rebuilt when a contextual
|
||||
* field instance is updated or CER pattern added/removed.
|
||||
*/
|
||||
function cer_ief_field_widget_form_alter(array &$element, array &$form_state, array $context) {
|
||||
// Only concerns fields within Inline Entity Forms.
|
||||
if (isset($context['form']['#ief_id'])) {
|
||||
// Get the form ID.
|
||||
$ief_id = $context['form']['#ief_id'];
|
||||
|
||||
// Get instance information for the IEF field.
|
||||
$ief_field_instance = $form_state['inline_entity_form'][$ief_id]['instance'];
|
||||
|
||||
// Check if "hide" is enabled on the IEF that is holding this field.
|
||||
$hide_cer_fields = !empty($ief_field_instance['widget']['settings']['type_settings']['hide_cer_fields']);
|
||||
|
||||
if ($hide_cer_fields) {
|
||||
// Get available CER chains. We use an ordinary static as this will be called for
|
||||
// each field that belongs to an IEF with 'hide' enabled -- could be a lot.
|
||||
static $plugins;
|
||||
|
||||
if (! isset($plugins)) {
|
||||
// Load available CER field keys into a map. The actual plugin info isn't needed.
|
||||
// We use drupal_map_assoc() so we can do isset() checks for plugins instead
|
||||
// of calling in_array().
|
||||
$plugins = drupal_map_assoc(array_keys(CerField::getPluginInfo()));
|
||||
}
|
||||
|
||||
// Set up filter chains for the affected entities. The left chain is for the entity
|
||||
// that has the IEF field on it, and the right chain is for the entity *in* the IEF.
|
||||
$left_chain = $ief_field_instance['entity_type'] . ':' . $ief_field_instance['bundle'] . ':' . $ief_field_instance['field_name'];
|
||||
$right_chain = $context['instance']['entity_type'] . ':' . $context['instance']['bundle'] . ':' . $context['instance']['field_name'];
|
||||
// Ensure that both fields are CER fields. If they're not, bail out.
|
||||
if (! isset($plugins[$left_chain], $plugins[$right_chain])) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If a preset from parent to IEF exists, prevent access to the field.
|
||||
foreach (_cer_filter_presets($left_chain) as $preset) {
|
||||
// Check if the preset's right hand points to the instance found in the IEF.
|
||||
if (strpos($preset->right, $right_chain) === 0) {
|
||||
$match = TRUE;
|
||||
}
|
||||
elseif ($preset->bidirectional && strpos($preset->left, $right_chain) === 0) {
|
||||
$match = TRUE;
|
||||
}
|
||||
|
||||
// Matching chain found. Prevent access to this field and return.
|
||||
if (isset($match)) {
|
||||
$element['#access'] = FALSE;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_cer_fields().
|
||||
*/
|
||||
function cer_profile2_cer_fields() {
|
||||
$fields = array();
|
||||
|
||||
// Create a fake field for each Profile2 type.
|
||||
foreach (array_keys(profile2_get_types()) as $profile_type) {
|
||||
// Profiles can only be attached to user accounts.
|
||||
$fields["user:user:profile_{$profile_type}"]['class'] = 'CerProfile2Field';
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_cer_fields_alter().
|
||||
*/
|
||||
function cer_profile2_cer_fields_alter(array &$fields) {
|
||||
foreach (array_keys($fields) as $identifier) {
|
||||
list ($entity_type, $bundle) = explode(':', $identifier);
|
||||
|
||||
// If this field is instantiated on a Profile2, make CER treat it like a field
|
||||
// collection by first setting its parent field, and setting the 'require parent'
|
||||
// flag so that CER won't allow it to stand alone in a field chain.
|
||||
if ($entity_type == 'profile2') {
|
||||
$fields[$identifier]['parents'][] = "user:user:profile_{$bundle}";
|
||||
$fields[$identifier]['require parent'] = TRUE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
name = "CER Profile2"
|
||||
core = "7.x"
|
||||
description = "Allows CER to relate user references to Profile2 fields."
|
||||
dependencies[] = cer
|
||||
dependencies[] = profile2
|
||||
|
||||
files[] = profile2.inc
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1455299962"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_disable().
|
||||
*/
|
||||
function cer_profile2_disable() {
|
||||
foreach (entity_load('cer', FALSE) as $preset) {
|
||||
if (_cer_profile2_is_profile2_preset($preset)) {
|
||||
$preset->wrapper->cer_enabled->set(FALSE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_uninstall().
|
||||
*/
|
||||
function cer_profile2_uninstall() {
|
||||
foreach (entity_load('cer', FALSE) as $preset) {
|
||||
if (_cer_profile2_is_profile2_preset($preset)) {
|
||||
entity_delete('cer', $preset->pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
define('CER_PROFILE2_PATTERN', '/^user:user:profile_/');
|
||||
|
||||
/**
|
||||
* Returns if either side of a preset refers to a profile2.
|
||||
*
|
||||
* @param \CerPreset $preset
|
||||
* The preset to test.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function _cer_profile2_is_profile2_preset(CerPreset $preset) {
|
||||
return preg_match(CER_PROFILE2_PATTERN, $preset->wrapper->cer_left->value()) || preg_match(CER_PROFILE2_PATTERN, $preset->wrapper->cer_right->value());
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_entity_property_info_alter().
|
||||
*/
|
||||
function cer_profile2_entity_property_info_alter(array &$info) {
|
||||
$struct = &$info['profile2']['properties']['cer']['property info'];
|
||||
|
||||
$struct['lineage']['getter callback'] = 'cer_profile2_get_profile2_lineage';
|
||||
$struct['depth']['getter callback'] = 'cer_profile2_get_profile2_depth';
|
||||
$struct['owner']['getter callback'] = 'cer_profile2_get_profile2_owner';
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity API getter callback. Returns the lineage of a Profile2 entity.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function cer_profile2_get_profile2_lineage(array $data, array $options, $property, $data_type, array $info) {
|
||||
return 'user:user:profile_' . $data[1]->type . ':profile2:' . $data[1]->type . ':';
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity API getter callback. Returns the depth of a Profile2. This is always
|
||||
* 1, since the profile is embedded directly under the user account as far
|
||||
* as CER is concerned.
|
||||
*
|
||||
* @return integer
|
||||
*/
|
||||
function cer_profile2_get_profile2_depth(array $data, array $options, $property, $data_type, array $info) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity API getter callback. Returns the user account which owns a Profile2.
|
||||
*
|
||||
* @return EntityDrupalWrapper.
|
||||
*/
|
||||
function cer_profile2_get_profile2_owner(array $data, array $options, $property, $data_type, array $info) {
|
||||
return new EntityDrupalWrapper('user', $data[1]->user());
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains a CER field plugin for referencing Profile2 entities. These references
|
||||
* are not actually fields at all, so this plugin is really more of a bridge to
|
||||
* trick CER into thinking that Profile2 is a reference field.
|
||||
*/
|
||||
|
||||
class CerProfile2Field extends CerField implements CerEntityContainerInterface {
|
||||
|
||||
protected $profileType;
|
||||
|
||||
/**
|
||||
* @override CerField::__construct().
|
||||
*/
|
||||
public function __construct(array $plugin) {
|
||||
$this->plugin = $plugin;
|
||||
list ($this->entityType, $this->bundle, $this->name) = explode(':', $plugin['identifier']);
|
||||
|
||||
$info = entity_get_info($this->entityType);
|
||||
// These "fields" can only be instantiated on user accounts, which are
|
||||
// normally not bundleable. However, there could be a module in the wild
|
||||
// which makes accounts bundleable, so let's not be presumptuous here.
|
||||
$this->isBundleable = (boolean) $info['entity keys']['bundle'];
|
||||
$this->entityTypeLabel = $info['label'];
|
||||
$this->bundleLabel = $info['bundles'][$this->bundle]['label'];
|
||||
// An account can only have one profile of this type.
|
||||
$this->cardinality = 1;
|
||||
$this->fieldTypeLabel = t('Profile');
|
||||
|
||||
// Load the Profile2 type information
|
||||
$this->profileType = profile2_get_types(subStr($this->name, 8));
|
||||
$this->label = $this->profileType->label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
// In effect, this "field" will "point to" Profile2 entities.
|
||||
return 'profile2';
|
||||
}
|
||||
|
||||
/**
|
||||
* @override CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
// This field can only "reference" one type of profile. There'll be
|
||||
// a separate instance of this plugin for each Profile2 type.
|
||||
return (array) $this->profileType->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerEntityContainerInterface::createInnerEntity().
|
||||
*/
|
||||
public function createInnerEntity(EntityDrupalWrapper $owner) {
|
||||
$init = array(
|
||||
'user' => $owner->value(),
|
||||
'type' => $this->profileType,
|
||||
);
|
||||
|
||||
// Create a blank profile for this user, and save it. The "reference" is implied
|
||||
// by the existence of the profile.
|
||||
$profile = profile2_create($init);
|
||||
$profile->save();
|
||||
|
||||
return $profile;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
name = "Field Object"
|
||||
description = "Provides a field type that can refer to field instances."
|
||||
|
||||
core = "7.x"
|
||||
|
||||
dependencies[] = options
|
||||
|
||||
files[] = includes/FieldChain.inc
|
||||
files[] = includes/FieldHierarchy.inc
|
||||
files[] = includes/FieldInstance.inc
|
||||
|
||||
; Information added by Drupal.org packaging script on 2016-02-12
|
||||
version = "7.x-3.0-alpha7+25-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1455299962"
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_field_schema().
|
||||
*/
|
||||
function field_object_field_schema(array $field) {
|
||||
return array(
|
||||
'columns' => array(
|
||||
'path' => array(
|
||||
'type' => 'text',
|
||||
'size' => 'tiny',
|
||||
'description' => 'The path to the instance, represented as text.',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes issue #2331553, and probably others.
|
||||
*/
|
||||
function field_object_update_7001() {
|
||||
db_update('field_config')
|
||||
->fields(array(
|
||||
'type' => 'field_object',
|
||||
'module' => 'field_object',
|
||||
))
|
||||
->condition('field_name', array('cer_left', 'cer_right'))
|
||||
->execute();
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Implements hook_theme().
|
||||
*/
|
||||
function field_object_theme() {
|
||||
return array(
|
||||
'field_object_label' => array(
|
||||
'variables' => array(
|
||||
'field' => array(),
|
||||
'instance' => array(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_info().
|
||||
*/
|
||||
function field_object_field_info() {
|
||||
return array(
|
||||
'field_object' => array(
|
||||
'label' => t('Field Reference'),
|
||||
'description' => t('Refers to a field instance.'),
|
||||
'settings' => array(),
|
||||
'instance_settings' => array(
|
||||
'function' => NULL,
|
||||
),
|
||||
'default_widget' => 'options_select',
|
||||
'default_formatter' => 'field_object_label',
|
||||
'no_ui' => TRUE,
|
||||
'property_type' => 'text',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_widget_info_alter().
|
||||
*/
|
||||
function field_object_field_widget_info_alter(array &$info) {
|
||||
$info['options_select']['field types'][] = 'field_config_reference';
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_formatter_info().
|
||||
*/
|
||||
function field_object_field_formatter_info() {
|
||||
return array(
|
||||
'field_object_label' => array(
|
||||
'label' => t('Label'),
|
||||
'description' => t("The field instance's label."),
|
||||
'field types' => array('field_object'),
|
||||
'settings' => array(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_is_empty().
|
||||
*/
|
||||
function field_object_field_is_empty(array $item, array $field) {
|
||||
return empty($item['path']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_field_formatter_view().
|
||||
*/
|
||||
function field_object_field_formatter_view($entity_type, $entity, array $field, array $instance, $language, array $items, array $display) {
|
||||
$element = array();
|
||||
|
||||
foreach ($items as $delta => $item) {
|
||||
$label = array();
|
||||
|
||||
foreach (_field_object_expand_path($item['path']) as $field) {
|
||||
$label[] = theme('field_object_label', $field);
|
||||
}
|
||||
|
||||
$element[$delta]['#markup'] = implode(' » ', $label);
|
||||
}
|
||||
|
||||
return $element;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_options_list().
|
||||
*/
|
||||
function field_object_options_list(array $field, array $instance, $entity_type, $entity) {
|
||||
return _field_object_build_hierarchy($field, $instance, $entity_type, $entity)->options();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a human-readable label for a field instance, including the entity
|
||||
* type and (if applicable) bundle that hosts it.
|
||||
*/
|
||||
function theme_field_object_label(array $variables) {
|
||||
$instance = $variables['instance'];
|
||||
|
||||
$output = '';
|
||||
|
||||
if ($instance['entity_type'] != 'field_collection_item') {
|
||||
$entity_type = entity_get_info($instance['entity_type']);
|
||||
$output = $entity_type['label'] . ' » ';
|
||||
|
||||
if ($entity_type['entity keys']['bundle']) {
|
||||
$output .= $entity_type['bundles'][ $instance['bundle'] ]['label'] . ' » ';
|
||||
}
|
||||
}
|
||||
|
||||
return $output . $instance['label'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function. Builds a FieldHierarchy object for the widget builder.
|
||||
*/
|
||||
function _field_object_build_hierarchy(array $field, array $instance, $entity_type, $entity) {
|
||||
$hierarchy = new FieldHierarchy();
|
||||
|
||||
// The instance should define a function which returns an array of FieldChain
|
||||
// objects to be added to the hierarchy.
|
||||
$function = $instance['settings']['function'];
|
||||
|
||||
if ($function && is_callable($function)) {
|
||||
$arguments = func_get_args();
|
||||
$chains = (array) call_user_func_array($function, $arguments);
|
||||
|
||||
array_walk($chains, array($hierarchy, 'addChain'));
|
||||
}
|
||||
|
||||
return $hierarchy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function. Expands a field reference's path value into an array
|
||||
* of field and instance definitions.
|
||||
*/
|
||||
function _field_object_expand_path($path) {
|
||||
$output = array();
|
||||
|
||||
foreach (explode('::', $path) as $instance) {
|
||||
list ($entity_type, $bundle, $field) = explode(':', $instance);
|
||||
|
||||
$output[] = array(
|
||||
'field' =>
|
||||
field_info_field($field),
|
||||
'instance' =>
|
||||
field_info_instance($entity_type, $field, $bundle),
|
||||
);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the FieldChain class.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* A doubly linked list of FieldInstance objects.
|
||||
*/
|
||||
class FieldChain implements SeekableIterator {
|
||||
|
||||
protected $chain = array();
|
||||
|
||||
protected $index = 0;
|
||||
|
||||
/**
|
||||
* Magic post-unserialization callback. Provides every field in the chain
|
||||
* with a reference to its parent (if any) and child (if any), effectively
|
||||
* turning the chain into a doubly linked list.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
foreach ($this->chain as $field) {
|
||||
if (isset($parent)) {
|
||||
$field->parent($parent)->child($field);
|
||||
}
|
||||
$parent = $field;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents this chain as a machine-readable string, separating the fields
|
||||
* with a T_PAAMAYIM_NEKUDOTAYIM (or, as we call it on planet Earth, a
|
||||
* double colon).
|
||||
*/
|
||||
public function __toString() {
|
||||
$key = array();
|
||||
|
||||
foreach ($this->chain as $field) {
|
||||
$key[] = $field->__toString();
|
||||
}
|
||||
|
||||
return implode('::', $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends a field instance to this chain. If $completed is passed, we'll
|
||||
* try to find the parents of the instance and recurse upwards, building
|
||||
* a tree of "routes" to the instance.
|
||||
*/
|
||||
public function addField(FieldInstance $field, array &$completed = NULL) {
|
||||
array_unshift($this->chain, $field);
|
||||
$this->__wakeup();
|
||||
|
||||
if (isset($completed)) {
|
||||
$parents = $field->getParents();
|
||||
|
||||
if ($parents) {
|
||||
foreach ($parents as $parent) {
|
||||
$branch = clone $this;
|
||||
$branch->addField($parent, $completed);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$completed[] = $this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last field in the chain.
|
||||
*/
|
||||
public function end() {
|
||||
return end($this->chain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements SeekableIterator::seek().
|
||||
*/
|
||||
public function seek($position) {
|
||||
if ($position >= 0 && $position < sizeof($this->chain)) {
|
||||
$this->index = $position;
|
||||
}
|
||||
else {
|
||||
throw new OutOfBoundsException(t('Cannot seek to invalid position %position.', array('%position' => $position)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::current().
|
||||
*/
|
||||
public function current() {
|
||||
return $this->chain[$this->index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::key().
|
||||
*/
|
||||
public function key() {
|
||||
return $this->current()->__toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::next().
|
||||
*/
|
||||
public function next() {
|
||||
$this->index++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::rewind().
|
||||
*/
|
||||
public function rewind() {
|
||||
$this->index = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::valid().
|
||||
*/
|
||||
public function valid() {
|
||||
return ($this->index < sizeof($this->chain));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the FieldHierarchy class.
|
||||
*/
|
||||
|
||||
class FieldHierarchy implements Countable {
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* The flattened hierarchy data.
|
||||
*/
|
||||
protected $data = array();
|
||||
|
||||
const ROOT = 'root';
|
||||
|
||||
public function __get($property) {
|
||||
return $this->{$property};
|
||||
}
|
||||
|
||||
public function options($key = FieldHierarchy::ROOT, $parent = NULL, $depth = -1) {
|
||||
$options = array();
|
||||
|
||||
$item = $this->data[$key];
|
||||
|
||||
if (isset($item['label'])) {
|
||||
$options[$key] = str_repeat('-', $depth) . $item['label'];
|
||||
}
|
||||
|
||||
if (isset($item['children'])) {
|
||||
foreach ($item['children'] as $child) {
|
||||
$options = array_merge($options, $this->options($child, $key, $depth + 1));
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an item of any type to the hierarchy.
|
||||
*/
|
||||
public function add($item_key, $label = NULL, $parent = FieldHierarchy::ROOT) {
|
||||
if (!array_key_exists($item_key, $this->data)) {
|
||||
$this->data[$item_key]['label'] = isset($label) ? $label : $item_key;
|
||||
}
|
||||
|
||||
if (!isset($this->data[$parent]['children'])) {
|
||||
$this->data[$parent]['children'] = array();
|
||||
}
|
||||
|
||||
if (!in_array($item_key, $this->data[$parent]['children'])) {
|
||||
$this->data[$parent]['children'][] = $item_key;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a single field plugin to the hierarchy.
|
||||
*/
|
||||
public function addField(FieldInstance $field) {
|
||||
$bundle_key = "{$field->entityType}:{$field->bundle}";
|
||||
|
||||
if ($field->isBundleable) {
|
||||
$this->add($field->entityType, $field->entityTypeLabel);
|
||||
$this->add($bundle_key, $field->bundleLabel, $field->entityType);
|
||||
}
|
||||
else {
|
||||
$this->add($bundle_key, $field->entityTypeLabel);
|
||||
}
|
||||
|
||||
$field_key = "{$bundle_key}:{$field->name}";
|
||||
$this->add($field_key, $field->label, $bundle_key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an entire field chain to the hierarchy.
|
||||
*/
|
||||
public function addChain(FieldChain $chain) {
|
||||
$parents = array();
|
||||
|
||||
foreach ($chain as $field) {
|
||||
if ($field->requireParent()) {
|
||||
$parent_key = implode('::', $parents);
|
||||
$field_key = "{$parent_key}::{$field}";
|
||||
|
||||
$this->add($field_key, $field->label, $parent_key);
|
||||
}
|
||||
else {
|
||||
$this->addField($field);
|
||||
}
|
||||
|
||||
$parents[] = $field->__toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @implements Countable::count().
|
||||
*/
|
||||
public function count() {
|
||||
return sizeof($this->data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
class FieldInstance {
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The instance's entity type.
|
||||
*/
|
||||
public $entityType;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The instance bundle.
|
||||
*/
|
||||
public $bundle;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The field's machine name.
|
||||
*/
|
||||
public $name;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
* Whether or not this instance's entity type supports bundles.
|
||||
*/
|
||||
public $isBundleable;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The human-readable label of the instance's entity type.
|
||||
*/
|
||||
public $entityTypeLabel;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The human-readable label of the instance's bundle.
|
||||
*/
|
||||
public $bundleLabel;
|
||||
|
||||
/**
|
||||
* @var integer
|
||||
* The cardinality (maximum values) the field supports, or
|
||||
* FIELD_CARDINALITY_UNLIMITED.
|
||||
*/
|
||||
public $cardinality;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The instance's label.
|
||||
*/
|
||||
public $label;
|
||||
|
||||
/**
|
||||
* @var FieldInstance
|
||||
* The parent of this instance, if any.
|
||||
*/
|
||||
protected $parent;
|
||||
|
||||
/**
|
||||
* @var FieldInstance
|
||||
* The child of this instance, if any.
|
||||
*/
|
||||
protected $child;
|
||||
|
||||
public function __construct($entity_type, $bundle, $field_name) {
|
||||
$this->entityType = $entity_type;
|
||||
$this->bundle = $bundle;
|
||||
$this->name = $field_name;
|
||||
|
||||
// Get info about the entity type and bundle hosting this field instance.
|
||||
$info = entity_get_info($entity_type);
|
||||
$this->isBundleable = (boolean) $info['entity keys']['bundle'];
|
||||
$this->entityTypeLabel = $info['label'];
|
||||
$this->bundleLabel = $info['bundles'][$bundle]['label'];
|
||||
|
||||
// Get global info about the field.
|
||||
$info = field_info_field($field_name);
|
||||
$this->cardinality = $info['cardinality'];
|
||||
|
||||
// Finally, get info about the field instance.
|
||||
$instance = field_info_instance($entity_type, $field_name, $bundle);
|
||||
$this->label = $instance['label'];
|
||||
}
|
||||
|
||||
public function __toString() {
|
||||
return "{$this->entityType}:{$this->bundle}:{$this->name}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or set the parent of this field instance.
|
||||
*/
|
||||
public function parent(FieldInstance $parent = NULL) {
|
||||
if ($parent) {
|
||||
$this->parent = $parent;
|
||||
}
|
||||
return $this->parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or set the child of this field instance.
|
||||
*/
|
||||
public function child(FieldInstance $child = NULL) {
|
||||
if ($child) {
|
||||
$this->child = $child;
|
||||
}
|
||||
return $this->child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if this field requires a parent. An example of this would be
|
||||
* a field that is instantiated on a field collection (which is itself
|
||||
* a field).
|
||||
*/
|
||||
public function requireParent() {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the parents of this field instance as an array of FieldInstance
|
||||
* objects. If there are no parents, return an empty array.
|
||||
*/
|
||||
public function getParents() {
|
||||
return array();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,457 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains base code for CER handlers, which are objects responsible for
|
||||
* creating, updating and deleting corresponding references between entities.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Exception related to CER operations.
|
||||
*/
|
||||
class CerException extends Exception {
|
||||
}
|
||||
|
||||
interface CerHandlerInterface {
|
||||
|
||||
/**
|
||||
* @constructor
|
||||
*
|
||||
* @param string $preset
|
||||
* The CER preset string, in the format:
|
||||
* entity_a*bundle_a*field_a*entity_b*bundle_b*field_b.
|
||||
*
|
||||
* @param $entity.
|
||||
* The local (home) entity to be wrapped by this instance.
|
||||
*/
|
||||
public function __construct($preset, $entity);
|
||||
|
||||
/**
|
||||
* Create reciprocal references on referenced entities after the
|
||||
* local entity has been created.
|
||||
*/
|
||||
public function insert();
|
||||
|
||||
/**
|
||||
* Delete reciprocal references on entities the local entity is no
|
||||
* longer referencing, and create new reciprocal references, after
|
||||
* the local entity has been updated.
|
||||
*/
|
||||
public function update();
|
||||
|
||||
/**
|
||||
* Delete all reciprocal references after the local entity is deleted.
|
||||
*/
|
||||
public function delete();
|
||||
|
||||
/**
|
||||
* Check if $entity is referenced by the local entity.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function references($entity);
|
||||
|
||||
/**
|
||||
* Check if the local entity is referenced by $entity.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entiy.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function referencedBy($entity);
|
||||
|
||||
/**
|
||||
* Check if the remote entity can reference the local entity, and vice-versa.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function referenceable($entity);
|
||||
|
||||
/**
|
||||
* Create a reference to the local entity on the remote entity, and vice-versa
|
||||
* if needed. Should throw CerException if the reference(s) can't be created
|
||||
* for any reason.
|
||||
*
|
||||
* @param object $entity
|
||||
*/
|
||||
public function reference($entity);
|
||||
|
||||
/**
|
||||
* Delete all references to the remote entity from the local entity,
|
||||
* and delete reciprocal references from the remote entity.
|
||||
*
|
||||
* @param object $entity.
|
||||
*/
|
||||
public function dereference($entity);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Base class for CER handlers. All this does is parse the preset
|
||||
* and store instance info about the local and remote fields.
|
||||
*/
|
||||
abstract class CerHandlerBase {
|
||||
|
||||
/**
|
||||
* Local field instance definition.
|
||||
*/
|
||||
protected $local;
|
||||
|
||||
/**
|
||||
* Remote field instance definition.
|
||||
*/
|
||||
protected $remote;
|
||||
|
||||
public function __construct($preset) {
|
||||
$keys = explode('*', $preset);
|
||||
|
||||
if (sizeof($keys) != 6) {
|
||||
throw new CerException(t('Invalid configuration: @preset', array('@preset' => $preset)));
|
||||
}
|
||||
|
||||
$this->local = field_info_instance($keys[0], $keys[2], $keys[1]);
|
||||
if ($this->local) {
|
||||
$this->local['field'] = field_info_field($keys[2]);
|
||||
}
|
||||
else {
|
||||
throw new CerException(t('Local field instance does not exist.'));
|
||||
}
|
||||
|
||||
$this->remote = field_info_instance($keys[3], $keys[5], $keys[4]);
|
||||
if ($this->remote) {
|
||||
$this->remote['field'] = field_info_field($keys[5]);
|
||||
}
|
||||
else {
|
||||
throw new CerException(t('Remote field instance does not exist.'));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Generic CER handler with rudimentary language handling.
|
||||
*/
|
||||
class CerHandler extends CerHandlerBase implements CerHandlerInterface {
|
||||
|
||||
/**
|
||||
* The local (home) entity.
|
||||
*/
|
||||
protected $entity;
|
||||
|
||||
/**
|
||||
* The local entity's ID.
|
||||
*/
|
||||
protected $id;
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::__construct().
|
||||
*/
|
||||
public function __construct($preset, $entity) {
|
||||
parent::__construct($preset);
|
||||
|
||||
// If $entity is of the wrong type, entity_extract_IDs()
|
||||
// will throw EntityMalformedException here.
|
||||
$extract_ids = entity_extract_IDs($this->local['entity_type'], $entity);
|
||||
$this->id = array_shift($extract_ids);
|
||||
|
||||
$this->entity = $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::insert().
|
||||
*/
|
||||
public function insert($ids = NULL) {
|
||||
|
||||
if (empty($ids)) {
|
||||
$entities = $this->getReferencedEntities();
|
||||
}
|
||||
else {
|
||||
$entities = entity_load($this->remote['entity_type'], $ids);
|
||||
}
|
||||
|
||||
foreach ($entities as $referenced_entity) {
|
||||
$this->reference($referenced_entity);
|
||||
_cer_update($this->remote['entity_type'], $referenced_entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::update().
|
||||
*/
|
||||
public function update() {
|
||||
$original = isset($this->entity->original) ? $this->entity->original : $this->entity;
|
||||
|
||||
$deleted = array_diff($this->getReferenceIDs($original, $this->local), $this->getLocalReferenceIDs());
|
||||
if ($deleted) {
|
||||
$entities = entity_load($this->remote['entity_type'], $deleted);
|
||||
foreach ($entities as $referenced_entity) {
|
||||
$this->dereference($referenced_entity);
|
||||
_cer_update($this->remote['entity_type'], $referenced_entity);
|
||||
}
|
||||
}
|
||||
|
||||
$added = array_diff($this->getLocalReferenceIDs(), $this->getReferenceIDs($original, $this->local));
|
||||
|
||||
if (!empty($added)) {
|
||||
$this->insert($added);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::delete().
|
||||
*/
|
||||
public function delete() {
|
||||
foreach ($this->getReferencedEntities() as $referenced_entity) {
|
||||
$this->dereference($referenced_entity);
|
||||
_cer_update($this->remote['entity_type'], $referenced_entity);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::references().
|
||||
*/
|
||||
public function references($entity) {
|
||||
return in_array($this->getRemoteEntityID($entity), $this->getLocalReferenceIDs());
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::referencedBy().
|
||||
*/
|
||||
public function referencedBy($entity) {
|
||||
return in_array($this->id, $this->getRemoteReferenceIDs($entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::referenceable().
|
||||
*/
|
||||
public function referenceable($entity) {
|
||||
$id = $this->getRemoteEntityID($entity);
|
||||
|
||||
$allowed = array(
|
||||
entityreference_get_selection_handler(
|
||||
$this->local['field'],
|
||||
$this->local,
|
||||
$this->local['entity_type'],
|
||||
$this->entity
|
||||
)
|
||||
->validateReferencableEntities(array($id)),
|
||||
entityreference_get_selection_handler(
|
||||
$this->remote['field'],
|
||||
$this->remote,
|
||||
$this->remote['entity_type'],
|
||||
$entity
|
||||
)
|
||||
->validateReferencableEntities(array($this->id)),
|
||||
);
|
||||
|
||||
return in_array($id, $allowed[0]) && in_array($this->id, $allowed[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::reference().
|
||||
*/
|
||||
public function reference($entity) {
|
||||
if ($this->referenceable($entity)) {
|
||||
try {
|
||||
$this->addReferenceTo($entity);
|
||||
}
|
||||
catch (CerException $e) {
|
||||
// Fail silently
|
||||
}
|
||||
|
||||
try {
|
||||
$this->addReferenceFrom($entity);
|
||||
}
|
||||
catch (CerException $e) {
|
||||
// Fail silently
|
||||
}
|
||||
}
|
||||
else {
|
||||
$variables = array(
|
||||
'!local_field' => $this->local['field_name'],
|
||||
'!local_type' => $this->local['entity_type'],
|
||||
'!local_id' => $this->id,
|
||||
'!remote_field' => $this->remote['field_name'],
|
||||
'!remote_type' => $this->remote['entity_type'],
|
||||
'!remote_id' => $this->getRemoteEntityID($entity),
|
||||
);
|
||||
watchdog('cer', 'Failed to reference !remote_field on !remote_type !remote_id from !local_field on !local_type !local_id.', $variables, WATCHDOG_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerHandlerInterface::dereference().
|
||||
*/
|
||||
public function dereference($entity) {
|
||||
if ($this->references($entity)) {
|
||||
$id = $this->getRemoteEntityID($entity);
|
||||
|
||||
foreach ($this->entity->{$this->local['field_name']} as $language => $references) {
|
||||
foreach ($references as $delta => $reference) {
|
||||
if ($reference['target_id'] == $id) {
|
||||
unset($this->entity->{$this->local['field_name']}[$language][$delta]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->referencedBy($entity)) {
|
||||
foreach ($entity->{$this->remote['field_name']} as $language => $references) {
|
||||
foreach ($references as $delta => $reference) {
|
||||
if ($reference['target_id'] == $this->id) {
|
||||
unset($entity->{$this->remote['field_name']}[$language][$delta]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a reference to the local entity on the remote entity. Throws CerException
|
||||
* if the local entity is already referenced by the remote entity, or if the remote
|
||||
* field cannot hold any more values.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*/
|
||||
protected function addReferenceFrom($entity) {
|
||||
if ($this->referencedBy($entity)) {
|
||||
throw new CerException(t('Cannot create duplicate reference from remote entity.'));
|
||||
}
|
||||
elseif ($this->filled($this->getRemoteReferenceIDs($entity), $this->remote['field'])) {
|
||||
throw new CerException(t('Remote field cannot support any more references.'));
|
||||
}
|
||||
else {
|
||||
$languages = field_available_languages($this->remote['entity_type'], $this->remote['field']);
|
||||
foreach ($languages as $language) {
|
||||
$entity->{$this->remote['field_name']}[$language][] = array('target_id' => $this->id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a reference to the remote entity on the local entity. Throws CerException
|
||||
* if the local entity already references the remote entity, or if the field cannot
|
||||
* hold any more values.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*/
|
||||
protected function addReferenceTo($entity) {
|
||||
$id = $this->getRemoteEntityID($entity);
|
||||
|
||||
if ($this->references($entity)) {
|
||||
throw new CerException(t('Cannot create duplicate reference to remote entity.'));
|
||||
}
|
||||
elseif ($this->filled($this->getLocalReferenceIDs(), $this->local['field'])) {
|
||||
throw new CerException(t('Local field cannot support any more references.'));
|
||||
}
|
||||
else {
|
||||
$languages = field_available_languages($this->local['entity_type'], $this->local['field']);
|
||||
foreach ($languages as $language) {
|
||||
$this->entity->{$this->local['field_name']}[$language][] = array('target_id' => $id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ID of the remote entity. If the entity is of the wrong type,
|
||||
* EntityMalformedException will be thrown.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*
|
||||
* @return mixed
|
||||
* The remote entity ID.
|
||||
*/
|
||||
protected function getRemoteEntityID($entity) {
|
||||
$extract_ids = entity_extract_IDs($this->remote['entity_type'], $entity);
|
||||
return array_shift($extract_ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the entities referenced by the local entity.
|
||||
*
|
||||
* @return array
|
||||
* Array of fully loaded referenced entities keyed by ID, or empty
|
||||
* array if nothing has been referenced.
|
||||
*/
|
||||
protected function getReferencedEntities() {
|
||||
$IDs = $this->getLocalReferenceIDs();
|
||||
return $IDs ? entity_load($this->remote['entity_type'], $IDs) : array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the IDs of the entities referenced by the local entity.
|
||||
*
|
||||
* @return array
|
||||
* Array of entity IDs, empty array if there are no references.
|
||||
*/
|
||||
protected function getLocalReferenceIDs() {
|
||||
return $this->getReferenceIDs($this->entity, $this->local);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the IDs of the entities referenced by $entity.
|
||||
*
|
||||
* @param object $entity
|
||||
* The remote entity.
|
||||
*
|
||||
* @return array
|
||||
* Array of entity IDs, empty array if there are no references.
|
||||
*/
|
||||
protected function getRemoteReferenceIDs($entity) {
|
||||
return $this->getReferenceIDs($entity, $this->remote);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a field can support any more values. Formerly known as
|
||||
* "reference overloading".
|
||||
*
|
||||
* @param array $references
|
||||
* The values in the field.
|
||||
*
|
||||
* @param $field
|
||||
* Field definition (i.e., from field_info_field).
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
private function filled($references, $field) {
|
||||
return $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && sizeof($references) >= $field['cardinality'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the referenced entity IDs from a specific field on $entity.
|
||||
*
|
||||
* @param object $entity
|
||||
* The entity to scan for references.
|
||||
*
|
||||
* @param array $field
|
||||
* Field or instance definition.
|
||||
*
|
||||
* @return array
|
||||
* Array of unique IDs, empty if there are no references or the field
|
||||
* does not exist on $entity.
|
||||
*/
|
||||
private function getReferenceIDs($entity, $field) {
|
||||
$IDs = array();
|
||||
if (isset($entity->{$field['field_name']})) {
|
||||
foreach ($entity->{$field['field_name']} as $references) {
|
||||
foreach ($references as $reference) {
|
||||
$IDs[] = $reference['target_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_unique(array_filter($IDs));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[intro]
|
||||
title = Introduction
|
||||
file = intro
|
||||
weight = 1
|
||||
|
||||
[presets]
|
||||
title = Presets
|
||||
file = presets
|
||||
weight = 2
|
||||
@@ -0,0 +1,17 @@
|
||||
<p>CER's purpose is to keep reference fields synchronized with each other.
|
||||
For example, if you have a node ("Alice") with a user reference field,
|
||||
and a user ("Bob") with a node reference field, and you make Alice
|
||||
reference Bob, CER will automatically give Bob a back-reference to Alice. If
|
||||
Alice subsequently dereferences Bob, Bob will automatically deference Alice.
|
||||
Or, if Alice is deleted, Bob will lose his reference to Alice. CER does all
|
||||
this transparently.</p>
|
||||
|
||||
<p>CER is a powerful module. It lets you create relationships between different
|
||||
"reference-type" fields. A <dfn>reference-type</dfn> field is, simply,
|
||||
any kind of field that references another entity. Out of the box, CER supports
|
||||
Entity Reference, Node Reference, User Reference, and core Taxonomy Term
|
||||
Reference fields. It also includes a pair of add-on modules supporting Profile2
|
||||
and Commerce Product Reference fields. CER also has an object-oriented plugin
|
||||
API that you can leverage if you need to support other types of reference
|
||||
fields or alter CER's behavior. (More information about CER's API
|
||||
can be found in cer.api.php.)</p>
|
||||
@@ -0,0 +1,49 @@
|
||||
<p>When you install CER, it won’t do anything at all until you create at least
|
||||
one <dfn>preset</dfn>. A preset is a relationship between two reference field
|
||||
instances, which are referred to as the left and right fields, respectively.
|
||||
When a change occurs in the left field, the right field will react — and
|
||||
vice-versa.</p>
|
||||
|
||||
<p>An example: suppose you have a user reference field called Author, and it
|
||||
lives on Page nodes. You also have a node reference field called My Pages, and
|
||||
it lives on users. You can set up a preset that looks like this:</p>
|
||||
|
||||
<p>Node: Page: Author <--> User: My Pages</p>
|
||||
|
||||
<p>In this case, Author is the left field and My Pages is the right field. When
|
||||
the Author field is changed on a Page node, the referenced user(s) will be
|
||||
given a back-reference to that node.</p>
|
||||
|
||||
<p>By default, presets are <dfn>bidirectional</dfn>. This means that a change
|
||||
on either side of the preset will affect the other side. The previous example
|
||||
is bidirectional: you can change Author or My Pages, and the other side
|
||||
will react accordingly.</p>
|
||||
|
||||
<p>It's possible to make a preset <dfn>one-directional</dfn>, which means that
|
||||
the right side will react when the left side changes, but NOT the other way
|
||||
around. In a one-directional preset, changes to the right field will have no
|
||||
effect on the left field.</p>
|
||||
|
||||
<p>A one-directional version of the above example would look like this:</p>
|
||||
|
||||
<p>Node: Page: Author —> User: My Pages</p>
|
||||
|
||||
<p>So what this means is that, in a bidirectional preset, it really doesn't
|
||||
matter which field is the left one and which is the right one. They’ll affect
|
||||
each other equally. But in a one-directional preset, it <em>does</em> matter
|
||||
which side you're on. CER allows you to "invert" (flip) a
|
||||
one-directional preset.</p>
|
||||
|
||||
<p>Internally, CER treats all reference-type fields the same way, which allows
|
||||
you to put a different kind of field on either side of a preset. You don't
|
||||
have to necessarily relate a node reference field to another node reference
|
||||
field. You could relate a node reference field to a user reference field. The
|
||||
only restriction is that each side of the preset must be able to reference the
|
||||
other side. So, to again use our example, Author needs to be able to reference
|
||||
users, and My Pages needs to be able to reference nodes (of the Page type).
|
||||
CER won't let you create relationships between fields that can’t actually
|
||||
relate.</p>
|
||||
|
||||
<p>CER presets are entities built on top of Entity API, and they can be
|
||||
imported and exported just like any other exportable entity type, including
|
||||
support for Features.</p>
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains CerEndPointIterator.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* The purpose of this iterator is to wrap around all the "endpoints" in a field chain.
|
||||
* An endpoint is a CerFieldHandler for a field that hasn't got a child. This is necessary
|
||||
* in order to support infinite levels of embedded entities (read: field collections).
|
||||
* This class is only instantiated by CerFieldChainHandler if its initial field handler
|
||||
* has a child (@see CerFieldHandler::__construct()).
|
||||
*/
|
||||
class CerEndPointIterator implements RecursiveIterator {
|
||||
|
||||
/**
|
||||
* @var CerField
|
||||
*/
|
||||
protected $field;
|
||||
|
||||
/**
|
||||
* @var CerFieldHandler
|
||||
*/
|
||||
protected $handler;
|
||||
|
||||
public function __construct(CerField $field, EntityDrupalWrapper $entity) {
|
||||
$this->field = $field;
|
||||
$this->handler = $field->getHandler($entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::current().
|
||||
*/
|
||||
public function current() {
|
||||
return $this->field->child()->getHandler($this->handler->current());
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::key().
|
||||
*/
|
||||
public function key() {
|
||||
return $this->handler->key();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::next().
|
||||
*/
|
||||
public function next() {
|
||||
$this->handler->next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::rewind().
|
||||
*/
|
||||
public function rewind() {
|
||||
$this->handler->rewind();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::handler().
|
||||
*/
|
||||
public function valid() {
|
||||
return $this->handler->valid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements RecursiveIterator::hasChildren().
|
||||
*/
|
||||
public function hasChildren() {
|
||||
return ($this->field->child() instanceof CerEntityContainerInterface);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements RecursiveIterator::getChildren().
|
||||
*/
|
||||
public function getChildren() {
|
||||
return new CerEndPointIterator($this->field->child(), $this->handler->current());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*
|
||||
* This interface should be implemented by field plugins which can create embedded
|
||||
* entities on the fly.
|
||||
*
|
||||
* The prime example is field collections. CER might need to add a backreference on
|
||||
* a field which is in a field collection, yet there might be no field collection items
|
||||
* on which to add the reference. In that case, a new field collection item must be
|
||||
* be created and referenced properly by the owner.
|
||||
*/
|
||||
interface CerEntityContainerInterface {
|
||||
|
||||
/**
|
||||
* Creates an embedded entity.
|
||||
*
|
||||
* @return EntityDrupalWrapper
|
||||
* The newly created embedded entity, in a metadata wrapper.
|
||||
*/
|
||||
public function createInnerEntity(EntityDrupalWrapper $owner);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the base class for CER field plugins.
|
||||
*
|
||||
* A field plugin tells CER how to interact with fields of a certain type. If a particular
|
||||
* field type integrates with Entity API, its CER plugin can be as simple as extending
|
||||
* CerField and implementing the getTargetType() method.
|
||||
*
|
||||
* @todo
|
||||
* More info about extending CerFieldHandler to further customize field plugins.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Represents a single field instance.
|
||||
*/
|
||||
abstract class CerField extends FieldInstance {
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* The plugin definition.
|
||||
*/
|
||||
protected $plugin;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $settings = array();
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public $fieldTypeLabel;
|
||||
|
||||
/**
|
||||
* Gets the type of entity that can be referenced by this field, e.g. 'node'.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract public function getTargetType();
|
||||
|
||||
/**
|
||||
* Constructor. Pretty self-explanatory!
|
||||
*/
|
||||
public function __construct(array $plugin) {
|
||||
// Store a copy of our plugin definition.
|
||||
$this->plugin = $plugin;
|
||||
|
||||
list ($entity_type, $bundle, $field_name) = explode(':', $plugin['identifier']);
|
||||
parent::__construct($entity_type, $bundle, $field_name);
|
||||
|
||||
// Store a copy of the field settings for convenience. At the time of this
|
||||
// writing, this is needed by the Entity Reference, Node Reference,
|
||||
// and Term Reference plugins.
|
||||
$info = field_info_field($this->name);
|
||||
$this->settings = $info['settings'];
|
||||
|
||||
$type_info = field_info_field_types($info['type']);
|
||||
$this->fieldTypeLabel = $type_info['label'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a CerFieldHandler subclass instance for the given entity.
|
||||
*
|
||||
* @param object $entity
|
||||
* The entity to be wrapped by the handler.
|
||||
*
|
||||
* @return CerFieldHandler
|
||||
*/
|
||||
public function getHandler(EntityDrupalWrapper $entity) {
|
||||
return new $this->plugin['handler']($this, $entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the bundles that this field instance can reference.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
$info = entity_get_info($this->getTargetType());
|
||||
return array_keys($info['bundles']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden.
|
||||
*/
|
||||
public function requireParent() {
|
||||
return $this->plugin['require parent'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden.
|
||||
*/
|
||||
public function getParents() {
|
||||
return array_map('CerField::getPlugin', $this->plugin['parents']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns information about a particular field plugin by its identifier, or all
|
||||
* available plugins (i.e., defined by hook_cer_fields()) if no identifier is given.
|
||||
* The aggregated result of hook_cer_fields() is statically cached.
|
||||
*/
|
||||
public static function getPluginInfo($identifier = NULL) {
|
||||
$info = &drupal_static(__METHOD__);
|
||||
|
||||
if (! isset($info)) {
|
||||
$info = module_invoke_all('cer_fields');
|
||||
|
||||
foreach ($info as $key => &$field) {
|
||||
$field += array(
|
||||
'identifier' =>
|
||||
$key,
|
||||
'parents' =>
|
||||
array(),
|
||||
'require parent' =>
|
||||
FALSE,
|
||||
'handler' =>
|
||||
'CerFieldHandler',
|
||||
);
|
||||
}
|
||||
drupal_alter('cer_fields', $info);
|
||||
}
|
||||
|
||||
return ($identifier ? (isset($info[$identifier]) ? $info[$identifier] : NULL) : $info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a single field plugin instance, by its identifier. All plugin instances
|
||||
* are statically cached.
|
||||
*
|
||||
* @param string $identifier
|
||||
* The plugin's identifier, in the format entity_type:bundle:field_name.
|
||||
*
|
||||
* @return CerField
|
||||
*
|
||||
* @throws Exception if there's no plugin for the given identifier. Why so harsh, you
|
||||
* ask? Because CerFieldChain::unpack() utterly depends on being able to get plugin
|
||||
* instances for every field in the chain, and if it can't, it could result in myriad
|
||||
* weird and serious problems. Throwing an exception will head that off at the pass.
|
||||
*/
|
||||
public static function getPlugin($identifier) {
|
||||
$instances = &drupal_static(__METHOD__);
|
||||
|
||||
if (! isset($instances[$identifier])) {
|
||||
$info = self::getPluginInfo($identifier);
|
||||
if ($info) {
|
||||
$instances[$identifier] = new $info['class']($info);
|
||||
}
|
||||
else {
|
||||
throw new Exception("Cannot get instance of invalid plugin $identifier.");
|
||||
}
|
||||
}
|
||||
|
||||
return $instances[$identifier];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CerFieldChain class.
|
||||
*/
|
||||
|
||||
class CerFieldChain extends FieldChain {
|
||||
|
||||
/**
|
||||
* Convenience method. Returns a handler for this chain in the context of
|
||||
* the given entity.
|
||||
*
|
||||
* @return CerFieldChainHandler
|
||||
*/
|
||||
public function getHandler(EntityDrupalWrapper $entity) {
|
||||
return new CerFieldChainHandler($this, $entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a regular expression to match field chain identifiers that this chain
|
||||
* can reference, e.g. /^node:(page|article):/
|
||||
*/
|
||||
public function regex() {
|
||||
$end = $this->end();
|
||||
return '/^' . $end->getTargetType() . ':(' . implode('|', $end->getTargetBundles()) . '):/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a Features export pipe for this chain, including every field and
|
||||
* field instance in it.
|
||||
*/
|
||||
public function export() {
|
||||
$pipe = array();
|
||||
|
||||
foreach ($this->chain as $field) {
|
||||
$pipe['field_instance'][] = "{$field->entityType}-{$field->bundle}-{$field->name}";
|
||||
}
|
||||
|
||||
return $pipe;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of every possible field chain for every field defined in
|
||||
* hook_cer_fields().
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function collectAll() {
|
||||
$chains = array();
|
||||
|
||||
foreach (array_keys(CerField::getPluginInfo()) as $identifier) {
|
||||
$chains = array_merge($chains, self::collect($identifier));
|
||||
}
|
||||
|
||||
return $chains;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of every possible field chain for a single field,
|
||||
* identified by its key in hook_cer_fields().
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function collect($identifier) {
|
||||
$chains = array();
|
||||
|
||||
$chain = new CerFieldChain();
|
||||
$chain->addField(CerField::getPlugin($identifier), $chains);
|
||||
|
||||
return $chains;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs and returns a CerFieldChain object from an encoded string
|
||||
* of field plugin identifiers glued together with ::.
|
||||
*
|
||||
* @return CerFieldChain
|
||||
*/
|
||||
public static function unpack($identifier) {
|
||||
$chain = new CerFieldChain();
|
||||
|
||||
foreach (array_reverse(explode('::', $identifier)) as $field) {
|
||||
$chain->addField(CerField::getPlugin($field));
|
||||
}
|
||||
|
||||
return $chain;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CerFieldChainHandler object.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Wraps around every CerFieldHandler object in a chain. In any given chain, there
|
||||
* could be many entities that need to be processed -- think about multi-value field
|
||||
* collections embedded within other multi-value field collections, and you quickly
|
||||
* see how extensive the recursion can be. CER needs to be able to handle crazy
|
||||
* scenarios like that and still perform add/delete operations transparently. That's
|
||||
* what this guy does.
|
||||
*/
|
||||
class CerFieldChainHandler {
|
||||
|
||||
/**
|
||||
* @var CerFieldChain
|
||||
*/
|
||||
protected $chain;
|
||||
|
||||
/**
|
||||
* @var EntityDrupalWrapper
|
||||
*/
|
||||
protected $entity;
|
||||
|
||||
/**
|
||||
* @var array or RecursiveIteratorIterator
|
||||
*/
|
||||
protected $handlers;
|
||||
|
||||
public function __construct(CerFieldChain $chain, EntityDrupalWrapper $entity) {
|
||||
$this->chain = $chain;
|
||||
$this->entity = $entity;
|
||||
|
||||
$chain->__wakeup();
|
||||
$chain->seek($entity->cer->depth->value());
|
||||
|
||||
$field = $chain->current();
|
||||
|
||||
// If the field has a child, there could be extensive recusion here. So we'll need
|
||||
// to iterate over the entire chain recursively -- luckily, SPL provides the
|
||||
// RecursiveIteratorIterator class for this purpose. But if there are no children,
|
||||
// we don't need to recurse; the only handler we'll need to load is the current
|
||||
// field's, for the current entity.
|
||||
if ($field->child()) {
|
||||
$this->handlers = new RecursiveIteratorIterator(new CerEndPointIterator($field, $entity));
|
||||
}
|
||||
else {
|
||||
// Wrap the handler in an array, just to normalize things internally.
|
||||
$this->handlers = array( $field->getHandler($entity) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the IDs of every entity referenced in this chain. If there are no references,
|
||||
* an empty array is returned.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getIDs() {
|
||||
$IDs = array();
|
||||
|
||||
foreach ($this->handlers as $handler) {
|
||||
$IDs = array_merge($handler->getIDs(), $IDs);
|
||||
}
|
||||
|
||||
return array_unique($IDs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a reference to the given entity.
|
||||
*/
|
||||
public function add(EntityDrupalWrapper $entity) {
|
||||
$owner = $this->entity;
|
||||
|
||||
foreach ($this->chain as $field) {
|
||||
// If the current field implements CerEntityContainerInterface, we can
|
||||
// create an entity on-the-fly to receive the reference, if there isn't
|
||||
// one already.
|
||||
if ($field instanceof CerEntityContainerInterface) {
|
||||
$items = $field->getHandler($owner);
|
||||
|
||||
// If there is are items which could receive the reference, seek to the
|
||||
// last one. Otherwise, create one.
|
||||
if (sizeof($items) == 0) {
|
||||
$owner = $field->createInnerEntity($owner);
|
||||
}
|
||||
else {
|
||||
$items->seek(-1);
|
||||
$owner = $items->current();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$field->getHandler($owner)->add($entity);
|
||||
}
|
||||
|
||||
public function delete(EntityDrupalWrapper $entity) {
|
||||
foreach ($this->handlers as $handler) {
|
||||
$handler->delete($entity);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains CerFieldHandler.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Handles low-level operations for a single field on a single entity. Exposes
|
||||
* methods to add, delete and check for references. This will also iterate over
|
||||
* the references, returning each one as an EntityDrupalWrapper object.
|
||||
*/
|
||||
class CerFieldHandler implements Countable, SeekableIterator {
|
||||
|
||||
/**
|
||||
* @var CerField
|
||||
*/
|
||||
protected $field;
|
||||
|
||||
/**
|
||||
* @var EntityDrupalWrapper
|
||||
*/
|
||||
protected $entity;
|
||||
|
||||
/**
|
||||
* @var EntityMetadataWrapper
|
||||
*/
|
||||
protected $value;
|
||||
|
||||
/**
|
||||
* @var integer
|
||||
*/
|
||||
protected $delta = 0;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $isMultiValue;
|
||||
|
||||
public function __construct(CerField $field, EntityDrupalWrapper $entity) {
|
||||
$this->field = $field;
|
||||
$this->entity = $entity;
|
||||
$this->value = $entity->{ $field->name };
|
||||
$this->isMultiValue = ($this->value instanceof EntityListWrapper);
|
||||
|
||||
$this->rewind();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a reference to $entity, validating it first.
|
||||
*
|
||||
* @param EntityDrupalWrapper $entity
|
||||
* The wrapped entity to reference.
|
||||
*/
|
||||
public function add(EntityDrupalWrapper $entity) {
|
||||
if ($this->validate($entity)) {
|
||||
$this->write();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all references to $entity.
|
||||
*
|
||||
* @param EntityDrupalWrapper $entity
|
||||
* The wrapped entity to dereference.
|
||||
*/
|
||||
public function delete(EntityDrupalWrapper $entity) {
|
||||
$entityID = $entity->getIdentifier();
|
||||
|
||||
if ($this->isMultiValue) {
|
||||
foreach ($this->value as $delta => $ref) {
|
||||
if ($entityID == $ref->getIdentifier()) {
|
||||
$this->value[$delta]->set(NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
elseif ($entityID == $this->value->getIdentifier()) {
|
||||
$this->value->set(NULL);
|
||||
}
|
||||
|
||||
$this->write();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a potential reference. After doing a cardinality check, the
|
||||
* reference is validated through the Field Attach API, allowing the module
|
||||
* which owns the field to do its normal validation logic. If validation
|
||||
* fails, the error(s) are logged.
|
||||
*
|
||||
* @param EntityDrupalWrapper $entity
|
||||
* The wrapped entity to validate.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
protected function validate(EntityDrupalWrapper $entity) {
|
||||
// Before we do anything else, check that the field has enough space to add the
|
||||
// reference. If there isn't, bail out so we don't blindly overwrite existing
|
||||
// field data.
|
||||
if ($this->checkCardinality()) {
|
||||
// Keep the previous value so we can restore it if validation fails.
|
||||
$prev_value = $this->value->value();
|
||||
|
||||
if ($this->isMultiValue) {
|
||||
$value = $this->value->value();
|
||||
$value[] = $entity->value();
|
||||
$this->value->set($value);
|
||||
}
|
||||
else {
|
||||
$this->value->set( $entity->value() );
|
||||
}
|
||||
|
||||
// Leverage the Field Attach API to validate the reference. If errors occur,
|
||||
// field_attach_validate() throws FieldValidationException, containing an array
|
||||
// of every validation error.
|
||||
try {
|
||||
// Only validate this field.
|
||||
field_attach_validate($this->entity->type(), $this->entity->value(), array('field_name' => $this->field->name));
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
catch (FieldValidationException $e) {
|
||||
foreach ($e->errors as $field) {
|
||||
foreach ($field as $language) {
|
||||
foreach ($language as $errors) {
|
||||
foreach ($errors as $error) {
|
||||
$this->logError($error['message'], $entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->value->set($prev_value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$this->logError('Cannot add reference to !that_link from !field_label on !this_link because there are no more slots available.', $entity);
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that there are enough slots in the field to add a reference.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
protected function checkCardinality() {
|
||||
return ($this->field->cardinality == FIELD_CARDINALITY_UNLIMITED ? TRUE : ($this->field->cardinality > $this->count()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves changes to the entity and resets the iterator.
|
||||
*/
|
||||
protected function write() {
|
||||
$entity_type = $this->entity->type();
|
||||
$entityID = $this->entity->getIdentifier();
|
||||
$entity = $this->entity->value();
|
||||
|
||||
$entity->cer_processed = TRUE;
|
||||
entity_save($entity_type, $entity);
|
||||
|
||||
// Reload the entity we just saved and cleared from the static cache.
|
||||
$entities = entity_load($entity_type, (array) $entityID);
|
||||
$this->entity->set($entities[$entityID]);
|
||||
|
||||
$this->__construct($this->field, $this->entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs an error, optionally against a specific entity. If the cer_debug
|
||||
* variable is set, the error will also be set as a message.
|
||||
*
|
||||
* @param string $message
|
||||
* The untranslated message to log.
|
||||
*
|
||||
* @param EntityDrupalWrapper $entity
|
||||
* The entity that has caused the error, if any.
|
||||
*/
|
||||
protected function logError($message, EntityDrupalWrapper $entity = NULL) {
|
||||
$variables = array(
|
||||
'!field_name' => $this->field->name,
|
||||
'!field_type' => $this->field->fieldTypeLabel,
|
||||
'!field_label' => $this->field->label,
|
||||
);
|
||||
|
||||
$variables['!this_type'] = $this->entity->type();
|
||||
$variables['!this_label'] = $this->entity->label();
|
||||
|
||||
// If the entity has a URI, provide a link to it. Otherwise, its "link"
|
||||
// will just be an unlinked label. Entity API doesn't reliably expose a url
|
||||
// property on entities, and there doesn't appear to be a way to check for
|
||||
// it without risking an EntityMetadataWrapperException. So I need to use
|
||||
// this clunky BS instead...ugh.
|
||||
$this_uri = entity_uri($this->entity->type(), $this->entity->value());
|
||||
if (isset($this_uri)) {
|
||||
$variables['!this_url'] = url($this_uri['path'], $this_uri['options']);
|
||||
$variables['!this_link'] = l($this->entity->label(), $this_uri['path'], $this_uri['options']);
|
||||
}
|
||||
else {
|
||||
$variables['!this_link'] = $this->entity->label();
|
||||
}
|
||||
|
||||
if ($entity) {
|
||||
$variables['!that_type'] = $entity->type();
|
||||
$variables['!that_label'] = $entity->label();
|
||||
|
||||
// If the entity has a URI, link to it.
|
||||
$that_uri = entity_uri($entity->type(), $entity->value());
|
||||
if (isset($that_uri)) {
|
||||
$variables['!that_url'] = url($that_uri['path'], $that_uri['options']);
|
||||
$variables['!that_link'] = l($entity->label(), $that_uri['path'], $that_uri['options']);
|
||||
}
|
||||
else {
|
||||
$variables['!that_link'] = $entity->label();
|
||||
}
|
||||
}
|
||||
|
||||
watchdog('cer', $message, $variables, WATCHDOG_ERROR);
|
||||
|
||||
if (variable_get('cer_debug', FALSE)) {
|
||||
drupal_set_message(t($message, $variables), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
public function getIDs() {
|
||||
$IDs = array();
|
||||
|
||||
if ($this->isMultiValue) {
|
||||
foreach ($this->value as $ref) {
|
||||
$IDs[] = $ref->raw();
|
||||
}
|
||||
}
|
||||
else {
|
||||
$IDs[] = $this->value->raw();
|
||||
}
|
||||
|
||||
return array_unique(array_filter($IDs));
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Countable::count().
|
||||
*/
|
||||
public function count() {
|
||||
if ($this->isMultiValue) {
|
||||
return sizeof($this->value);
|
||||
}
|
||||
else {
|
||||
return ($this->value->value() ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements SeekableIterator::seek().
|
||||
*/
|
||||
public function seek($position) {
|
||||
$length = $this->count();
|
||||
|
||||
if ($position < 0) {
|
||||
$position += $length;
|
||||
}
|
||||
|
||||
if ($position >= 0 && $position < $length) {
|
||||
$this->delta = $position;
|
||||
}
|
||||
else {
|
||||
throw new OutOfBoundsException(t('Cannot seek to invalid position.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::current().
|
||||
*/
|
||||
public function current() {
|
||||
return ($this->isMultiValue ? $this->value[$this->delta] : $this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::key().
|
||||
*/
|
||||
public function key() {
|
||||
return $this->current()->getIdentifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::next().
|
||||
*/
|
||||
public function next() {
|
||||
$this->delta++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::rewind().
|
||||
*/
|
||||
public function rewind() {
|
||||
$this->delta = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Iterator::valid().
|
||||
*/
|
||||
public function valid() {
|
||||
return ($this->delta < $this->count());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the entity class for CER presets.
|
||||
*/
|
||||
|
||||
class CerPreset extends Entity {
|
||||
|
||||
/**
|
||||
* @var integer
|
||||
* The preset's numeric ID in the database.
|
||||
*/
|
||||
public $pid = 0;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The export identifier, in the format $this->cer_left*$this->cer_right.
|
||||
*/
|
||||
public $identifier;
|
||||
|
||||
/**
|
||||
* @var EntityMetadataWrapper
|
||||
* A metadata wrapper around this preset, for convenience.
|
||||
*/
|
||||
public $wrapper;
|
||||
|
||||
/**
|
||||
* @var integer
|
||||
* The exportable status of this preset.
|
||||
*/
|
||||
public $status = 0x01; // ENTITY_CUSTOM
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* The module exporting this preset.
|
||||
*/
|
||||
public $module = 'cer';
|
||||
|
||||
/**
|
||||
* Overrides Entity::__construct().
|
||||
*/
|
||||
public function __construct(array $values = array()) {
|
||||
parent::__construct($values, 'cer');
|
||||
$this->wrapper = new EntityDrupalWrapper('cer', $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides Entity::label().
|
||||
*/
|
||||
public function label() {
|
||||
return isset($this->label_variables) ? t('@left !operator @right', $this->label_variables) : $this->defaultLabel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides Entity::save().
|
||||
*/
|
||||
public function save() {
|
||||
// Generate the export identifier automagically before saving.
|
||||
$this->identifier = $this->wrapper->cer_left->value() . '*' . $this->wrapper->cer_right->value();
|
||||
parent::save();
|
||||
}
|
||||
|
||||
public function invert() {
|
||||
$init = get_object_vars($this);
|
||||
|
||||
unset($init['pid'], $init['wrapper'], $init['identifier'], $init['status']);
|
||||
|
||||
$buf = $init['cer_left'];
|
||||
$init['cer_left'] = $init['cer_right'];
|
||||
$init['cer_right'] = $buf;
|
||||
|
||||
return entity_create('cer', $init);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* The controller class for CerPreset entities.
|
||||
*/
|
||||
class CerPresetController extends EntityAPIControllerExportable {
|
||||
|
||||
/**
|
||||
* Overridden.
|
||||
*/
|
||||
public function export($entity, $prefix = '') {
|
||||
$variables = get_object_vars($entity);
|
||||
|
||||
// I really wish Entity API tried to notify the entity that it's being
|
||||
// exported so that it could clean itself up first, but it doesn't. So we
|
||||
// gotta do this bizness.
|
||||
unset($variables['pid'], $variables['wrapper'], $variables['status'], $variables['module'], $variables['label_variables'], $variables['uid']);
|
||||
// Features 2.x checks for overriddenness using sorted keys, which means
|
||||
// that if the variables aren't key-sorted the presets will always be
|
||||
// considered overridden, even if they actually aren't.
|
||||
ksort($variables);
|
||||
|
||||
return entity_var_json_export($variables, $prefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden.
|
||||
*/
|
||||
protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
|
||||
parent::attachLoad($queried_entities, $revision_id);
|
||||
|
||||
foreach ($queried_entities as $preset) {
|
||||
// Attach variables used to build the human-readable preset label. These
|
||||
// need to be attached after the Field API has done its magic (i.e.,
|
||||
// during parent::attachLoad()), since the label depends on field values.
|
||||
// @see CerPreset::label().
|
||||
$fields = field_attach_view('cer', $preset, 'default');
|
||||
|
||||
$preset->label_variables = array(
|
||||
'@left' =>
|
||||
render($fields['cer_left'][0]),
|
||||
'@right' =>
|
||||
render($fields['cer_right'][0]),
|
||||
'!operator' =>
|
||||
$preset->wrapper->cer_bidirectional->value() ? '<>' : '>',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Contains the controller class for exporting CER presets via Features.
|
||||
*/
|
||||
|
||||
class CerPresetFeaturesController extends EntityDefaultFeaturesController {
|
||||
|
||||
/**
|
||||
* Overridden.
|
||||
*/
|
||||
public function export($data, &$export, $module = '') {
|
||||
$pipe = parent::export($data, $export, $module);
|
||||
|
||||
// Every field in both chains may need to export additional things (the
|
||||
// field base and instance definitions at least, plus any extra dependencies).
|
||||
// All that logic is delegated to CerFieldChain.
|
||||
foreach (entity_load_multiple_by_name($this->type, $data) as $preset) {
|
||||
$pipe = array_merge_recursive($pipe, $preset->wrapper->cer_left->chain->value()->export());
|
||||
$pipe = array_merge_recursive($pipe, $preset->wrapper->cer_right->chain->value()->export());
|
||||
}
|
||||
|
||||
return $pipe;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This class is a unified way for CER to find the presets that apply to a given
|
||||
* entity. The result set is segmented into two parts: presets where the entity
|
||||
* is on the left side, and bidirectional presets with the entity on the right
|
||||
* side (i.e., the ones which need to be inverted before use). The execute()
|
||||
* method will return a merged and sorted array of presets, but the segmented
|
||||
* result set is exposed to the world as well for other uses (i.e., CER Entity
|
||||
* Settings' selection handler).
|
||||
*/
|
||||
class CerPresetFinder extends EntityFieldQuery {
|
||||
|
||||
public $result = array();
|
||||
|
||||
protected $entity;
|
||||
|
||||
public function __construct(EntityDrupalWrapper $entity) {
|
||||
$this->entity = $entity;
|
||||
|
||||
$this
|
||||
->entityCondition('entity_type', 'cer')
|
||||
->addTag('cer_presets')
|
||||
->addMetaData('entity', $entity);
|
||||
}
|
||||
|
||||
public function execute() {
|
||||
$lineage = $this->entity->cer->lineage->value();
|
||||
|
||||
$this->result['cer'] = $this
|
||||
->fieldCondition('cer_enabled', 'value', TRUE)
|
||||
->fieldCondition('cer_left', 'path', $lineage, 'STARTS_WITH')
|
||||
->_load(parent::execute());
|
||||
|
||||
$this->fieldConditions = array();
|
||||
|
||||
$this->result['cer__invert'] = $this
|
||||
->fieldCondition('cer_enabled', 'value', TRUE)
|
||||
->fieldCondition('cer_bidirectional', 'value', TRUE)
|
||||
->fieldCondition('cer_right', 'path', $lineage, 'STARTS_WITH')
|
||||
->_load(parent::execute());
|
||||
|
||||
$result = $this->result['cer'];
|
||||
foreach ($this->result['cer__invert'] as $preset) {
|
||||
$result[] = $preset->invert();
|
||||
}
|
||||
usort($result, array($this, '_sort'));
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function _load(array $result) {
|
||||
return isset($result['cer']) ? entity_load('cer', array_keys($result['cer'])) : array();
|
||||
}
|
||||
|
||||
private function _sort(CerPreset $a, CerPreset $b) {
|
||||
$a_weight = $a->wrapper->cer_weight->value();
|
||||
$b_weight = $b->wrapper->cer_weight->value();
|
||||
|
||||
if ($a_weight > $b_weight) {
|
||||
return 1;
|
||||
}
|
||||
elseif ($b_weight > $a_weight) {
|
||||
return -1;
|
||||
}
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains CerPresetHandler.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class
|
||||
* Contains the logic for performing CER operations on a single entity,
|
||||
* using a single preset.
|
||||
*/
|
||||
class CerPresetHandler {
|
||||
|
||||
/**
|
||||
* @var CerFieldChain
|
||||
*/
|
||||
protected $left;
|
||||
|
||||
/**
|
||||
* @var CerFieldChain
|
||||
*/
|
||||
protected $right;
|
||||
|
||||
/**
|
||||
* @var EntityDrupalWrapper
|
||||
*/
|
||||
protected $entity;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $refIDs;
|
||||
|
||||
public function __construct(CerPreset $preset, EntityDrupalWrapper $entity) {
|
||||
$this->left = $preset->wrapper->cer_left->chain->value();
|
||||
$this->right = $preset->wrapper->cer_right->chain->value();
|
||||
$this->entity = $entity;
|
||||
|
||||
// Store the current set of reference IDs so that we only need to instantiate
|
||||
// the left handler once.
|
||||
$this->refIDs = $this->left->getHandler( $entity )->getIDs();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an entity insert. This loops through the referenced entity $IDs and
|
||||
* adds a reference to this entity if the reference doesn't already have one.
|
||||
*/
|
||||
public function insert(array $IDs = array()) {
|
||||
// If no IDs were passed in, use the current reference set.
|
||||
$IDs = ($IDs ? $IDs : $this->refIDs);
|
||||
|
||||
// Get this entity's ID right now, so we don't have to keep calling
|
||||
// $this->entity->cer->owner->getIdentifier(). Hooray for micro-optimization!
|
||||
$myID = $this->entity->cer->owner->getIdentifier();
|
||||
|
||||
foreach ($this->load( $IDs ) as $ref) {
|
||||
$handler = $this->right->getHandler( $ref );
|
||||
|
||||
// Only create the backreference if the reference doesn't already reference
|
||||
// this entity (which it might, if there is more than one preset that references
|
||||
// a single field instance).
|
||||
if (! in_array($myID, $handler->getIDs())) {
|
||||
$handler->add( $this->entity->cer->owner );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an entity update. This could be either a normal update done by a user,
|
||||
* or a bulk update.
|
||||
*/
|
||||
public function update() {
|
||||
// Get the previous set of reference IDs. $entity->cer->original will return either
|
||||
// $entity->original, if it exists, or the current entity. So, if this is a bulk
|
||||
// update, $originalIDs will be identical to $this->refIDs.
|
||||
$originalIDs = $this->left->getHandler( $this->entity->cer->original )->getIDs();
|
||||
|
||||
// If there are any references that were in the previous set but not the current
|
||||
// set, delete those backreferences. Under normal circumstances, there will be
|
||||
// nothing to delete during a bulk update, since the previous set and current
|
||||
// set should be identical.
|
||||
$deleted = array_diff($originalIDs, $this->refIDs);
|
||||
if ($deleted) {
|
||||
$this->delete($deleted);
|
||||
}
|
||||
|
||||
// If the previous set is identical to the current set, we'll be processing
|
||||
// all existing references (see the first line of $this->insert()).
|
||||
$added = array_diff($this->refIDs, $originalIDs);
|
||||
$this->insert($added);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an entity delete. Loops through the referenced entity IDs and clears
|
||||
* their references to this entity.
|
||||
*/
|
||||
public function delete(array $IDs = array()) {
|
||||
// As with $this->insert(), we can process a specific set of references or
|
||||
// everything in the current set.
|
||||
$IDs = ($IDs ? $IDs : $this->refIDs);
|
||||
|
||||
foreach ($this->load( $IDs ) as $ref) {
|
||||
$this->right->getHandler( $ref )->delete( $this->entity->cer->owner );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads referenced entities. This might seem like a convenience method, but it
|
||||
* is a critical part CER's core logic.
|
||||
*
|
||||
* @param array $IDs
|
||||
* Array of entity IDs to load.
|
||||
*
|
||||
* @return array
|
||||
* The requested entities, wrapped by EntityDrupalWrapper. If nothing could be
|
||||
* loaded, an empty array is returned.
|
||||
*/
|
||||
protected function load(array $IDs) {
|
||||
if (empty($IDs)) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$this->right->rewind();
|
||||
$right = $this->right->current();
|
||||
$entity_type = $right->entityType;
|
||||
|
||||
$query = new EntityFieldQuery();
|
||||
$query->entityCondition('entity_type', $entity_type);
|
||||
$query->entityCondition('entity_id', $IDs);
|
||||
|
||||
// If the right entity type has bundles, we need to filter by that too. If we don't,
|
||||
// we could run into a bug where, if the left field can reference multiple bundles,
|
||||
// we might try to modify the wrong entity. Essentially, the loading of referenced
|
||||
// entities should be as targeted as possible to prevent ambiguities and buggery.
|
||||
if ($right->isBundleable) {
|
||||
$query->entityCondition('bundle', $right->bundle);
|
||||
}
|
||||
|
||||
$result = $query->execute();
|
||||
if (isset($result[$entity_type])) {
|
||||
$result[$entity_type] = entity_load($entity_type, array_keys($result[$entity_type]));
|
||||
|
||||
foreach ($result[$entity_type] as $id => $entity) {
|
||||
$result[$entity_type][$id] = new EntityDrupalWrapper($entity_type, $entity);
|
||||
}
|
||||
|
||||
return $result[$entity_type];
|
||||
}
|
||||
else {
|
||||
return array();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Contains the controller class for CER's UI (i.e., preset management pages),
|
||||
* used by Entity API.
|
||||
*/
|
||||
|
||||
class CerUIController extends EntityDefaultUIController {
|
||||
|
||||
public function hook_menu() {
|
||||
$items = parent::hook_menu();
|
||||
|
||||
$items[$this->path]['title'] = t('Corresponding Entity References');
|
||||
$items["{$this->path}/list"]['title'] = t('Presets');
|
||||
|
||||
$this->setTitle($items["{$this->path}/add"], t('Add preset'));
|
||||
$this->setTitle($items["{$this->path}/import"], t('Import preset'));
|
||||
|
||||
$items["{$this->path}/manage/%entity_object/toggle"] = $this->createCallback('cer_toggle_preset', 'update');
|
||||
$items["{$this->path}/manage/%entity_object/invert"] = $this->createCallback('cer_invert_preset', 'create');
|
||||
|
||||
// Don't provide a page for cloning a preset.
|
||||
unset($items["{$this->path}/manage/%entity_object/clone"]);
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function createCallback($function, $operation, array $init = array()) {
|
||||
return $init + array(
|
||||
'type' => MENU_CALLBACK,
|
||||
'page callback' => $function,
|
||||
'page arguments' => array(5),
|
||||
'load arguments' => array('cer'),
|
||||
'access callback' => 'entity_access',
|
||||
'access arguments' => array($operation, 'cer'),
|
||||
'file' => 'cer.admin.inc',
|
||||
'file path' => drupal_get_path('module', 'cer'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a static title on a menu item.
|
||||
*/
|
||||
private function setTitle(array &$item, $title) {
|
||||
$item['title'] = $title;
|
||||
unset($item['title callback'], $item['title arguments']);
|
||||
}
|
||||
|
||||
public function operationForm($form, &$form_state, $entity, $action) {
|
||||
switch ($action) {
|
||||
case 'delete':
|
||||
return confirm_form($form, t('Are you sure you want to delete this preset?'), $this->path, t('@left will no longer synchronize with @right.', $entity->label_variables));
|
||||
|
||||
default:
|
||||
return parent::operationForm($form, $form_state, $entity, $action);
|
||||
}
|
||||
}
|
||||
|
||||
public function overviewForm($form, &$form_state) {
|
||||
$form = parent::overviewForm($form, $form_state);
|
||||
|
||||
$form['actions'] = array(
|
||||
'update' => array(
|
||||
'#type' => 'submit',
|
||||
'#value' => t('Save changes'),
|
||||
),
|
||||
'#type' => 'actions',
|
||||
);
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
public function overviewFormSubmit($form, &$form_state) {
|
||||
foreach ($form_state['values']['table'] as $id => $values) {
|
||||
$preset = entity_object_load($id, $this->entityType);
|
||||
|
||||
$preset->wrapper->cer_enabled->set($values['cer_enabled'][LANGUAGE_NONE][0]['value']);
|
||||
$preset->wrapper->cer_bidirectional->set($values['cer_bidirectional'][LANGUAGE_NONE][0]['value']);
|
||||
$preset->wrapper->cer_weight->set($values['cer_weight'][LANGUAGE_NONE][0]['value']);
|
||||
|
||||
$preset->save();
|
||||
}
|
||||
|
||||
drupal_set_message(t('The changes have been saved.'));
|
||||
}
|
||||
|
||||
public function overviewTable($conditions = array()) {
|
||||
$render = array(
|
||||
'#header' => array(
|
||||
t('Left Field'),
|
||||
t('Right Field'),
|
||||
t('Status'),
|
||||
t('Enabled'),
|
||||
t('Bidirectional'),
|
||||
t('Weight'),
|
||||
t('Operations'),
|
||||
),
|
||||
'#tabledrag' => array(
|
||||
array(
|
||||
'action' => 'order',
|
||||
'relationship' => 'sibling',
|
||||
'group' => 'cer-weight',
|
||||
),
|
||||
),
|
||||
'#empty' => t('None.'),
|
||||
'#type' => 'table',
|
||||
);
|
||||
|
||||
$query = new EntityFieldQuery();
|
||||
$query->entityCondition('entity_type', $this->entityType);
|
||||
|
||||
// Add all conditions to query.
|
||||
foreach ($conditions as $key => $value) {
|
||||
$query->propertyCondition($key, $value);
|
||||
}
|
||||
|
||||
if ($this->overviewPagerLimit) {
|
||||
$query->pager($this->overviewPagerLimit);
|
||||
}
|
||||
|
||||
$query->fieldOrderBy('cer_weight', 'value');
|
||||
|
||||
$results = $query->execute();
|
||||
$entities = isset($results['cer']) ? entity_load('cer', array_keys($results['cer'])) : array();
|
||||
|
||||
foreach ($entities as $entity) {
|
||||
$render[$entity->pid] = $this->overviewTableRow($conditions, $entity->pid, $entity);
|
||||
}
|
||||
|
||||
return $render;
|
||||
}
|
||||
|
||||
protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {
|
||||
$render_fields = field_attach_view($this->entityType, $entity, 'default');
|
||||
|
||||
$render_fields['cer_left']['#label_display'] = 'inline';
|
||||
$render_fields['cer_left']['#title'] = $entity->wrapper->cer_left->chain->value()->end()->fieldTypeLabel;
|
||||
$row['cer_left'] = $render_fields['cer_left'];
|
||||
|
||||
$render_fields['cer_right']['#label_display'] = 'inline';
|
||||
$render_fields['cer_right']['#title'] = $entity->wrapper->cer_right->chain->value()->end()->fieldTypeLabel;
|
||||
$row['cer_right'] = $render_fields['cer_right'];
|
||||
|
||||
$row['status'] = array(
|
||||
'#theme' => 'entity_status',
|
||||
'#status' => $entity->status,
|
||||
);
|
||||
|
||||
$form_fields = array();
|
||||
$form_state = form_state_defaults();
|
||||
$form_state['build_info']['form_id'] = 'cer_overview_form';
|
||||
field_attach_form($this->entityType, $entity, $form_fields, $form_state);
|
||||
|
||||
unset($form_fields['cer_enabled'][LANGUAGE_NONE]['#title']);
|
||||
$row['cer_enabled'] = $form_fields['cer_enabled'];
|
||||
|
||||
unset($form_fields['cer_bidirectional'][LANGUAGE_NONE]['#title']);
|
||||
$row['cer_bidirectional'] = $form_fields['cer_bidirectional'];
|
||||
|
||||
unset($form_fields['cer_weight'][LANGUAGE_NONE]['#title']);
|
||||
$form_fields['cer_weight'][LANGUAGE_NONE]['#attributes']['class'][] = 'cer-weight';
|
||||
$row['cer_weight'] = $form_fields['cer_weight'];
|
||||
|
||||
// Add in any passed additional cols.
|
||||
foreach ($additional_cols as $key => $col) {
|
||||
$row[$key] = $col;
|
||||
}
|
||||
|
||||
// I like drop buttons more than an inline set of links.
|
||||
$links = array(
|
||||
'toggle' => array(
|
||||
'title' => $entity->wrapper->cer_enabled->value() ? t('disable') : t('enable'),
|
||||
'href' => "{$this->path}/manage/{$id}/toggle",
|
||||
'query' => drupal_get_destination(),
|
||||
),
|
||||
'edit' => array(
|
||||
'title' => t('edit'),
|
||||
'href' => "{$this->path}/manage/{$id}",
|
||||
),
|
||||
);
|
||||
|
||||
// If the preset is one-directional, expose a link to invert it.
|
||||
if (! $entity->wrapper->cer_bidirectional->value()) {
|
||||
$links['invert'] = array(
|
||||
'title' => t('invert'),
|
||||
'href' => "{$this->path}/manage/{$id}/invert",
|
||||
'query' => drupal_get_destination(),
|
||||
);
|
||||
}
|
||||
|
||||
if (entity_has_status($this->entityType, $entity, ENTITY_OVERRIDDEN)) {
|
||||
$links['revert'] = array(
|
||||
'title' => t('revert'),
|
||||
'href' => "{$this->path}/manage/{$id}/revert",
|
||||
'query' => drupal_get_destination(),
|
||||
);
|
||||
}
|
||||
else {
|
||||
$links['delete'] = array(
|
||||
'title' => t('delete'),
|
||||
'href' => "{$this->path}/manage/{$id}/delete",
|
||||
'query' => drupal_get_destination(),
|
||||
);
|
||||
}
|
||||
$links['export'] = array(
|
||||
'title' => t('export'),
|
||||
'href' => "{$this->path}/manage/{$id}/export",
|
||||
);
|
||||
|
||||
$row['operations'] = array(
|
||||
'#theme' => 'links__ctools_dropbutton',
|
||||
'#links' => $links,
|
||||
);
|
||||
|
||||
$row['#attributes']['class'][] = 'draggable';
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CER plugin for Entity Reference fields.
|
||||
*/
|
||||
|
||||
class CerEntityReferenceField extends CerField {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return $this->settings['target_type'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @override CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
$bundles = array();
|
||||
|
||||
// If the reference field is using a view, load the view and see if it's filtering by the entity
|
||||
// type's bundle filter. If it is, the filter values are the target bundles. Otherwise,
|
||||
// assume that all bundles can be referenced.
|
||||
//
|
||||
// @todo Support contextual filters?
|
||||
//
|
||||
// NOTE: Selection handlers (i.e., $field['settings']['handler']) are plugins owned by
|
||||
// Entity Reference. There is no method defined to get an array of referenceable
|
||||
// bundles, but hopefully, if CER gains enough traction in the community, such a
|
||||
// method can be added to the EntityReference_SelectionHandler interface. This
|
||||
// function could then be deprecated, which would be a more flexible, future-proof
|
||||
// method of finding a field's target bundles.
|
||||
//
|
||||
if ($this->settings['handler'] == 'views') {
|
||||
$view = views_get_view($this->settings['handler_settings']['view']['view_name']);
|
||||
$view->set_display($this->settings['handler_settings']['view']['display_name']);
|
||||
|
||||
$info = entity_get_info($this->getTargetType());
|
||||
if (isset($info['entity keys']['bundle'])) {
|
||||
$handler = $view->display_handler->get_handler('filter', $info['entity keys']['bundle']);
|
||||
if ($handler) {
|
||||
$bundles = $handler->value;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$bundles = $this->settings['handler_settings']['target_bundles'];
|
||||
}
|
||||
|
||||
return ($bundles ? $bundles : parent::getTargetBundles());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CER plugin for Field Collection fields.
|
||||
*/
|
||||
|
||||
class CerFieldCollectionField extends CerField implements CerEntityContainerInterface {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return 'field_collection_item';
|
||||
}
|
||||
|
||||
/**
|
||||
* @override CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
return array($this->name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements CerEntityContainerInterface::createInnerEntity().
|
||||
*/
|
||||
public function createInnerEntity(EntityDrupalWrapper $owner) {
|
||||
// Create an empty field collection item.
|
||||
$collection = new EntityDrupalWrapper('field_collection_item', entity_create('field_collection_item', array('field_name' => $this->name)));
|
||||
$collection->host_entity->set( $owner );
|
||||
$collection->save(TRUE);
|
||||
|
||||
// 'Reference' the newly created field collection item.
|
||||
$this->getHandler($owner)->add($collection);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CER plugin for Node Reference fields.
|
||||
*/
|
||||
|
||||
class CerNodeReferenceField extends CerField {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return 'node';
|
||||
}
|
||||
|
||||
/**
|
||||
* @override CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
$bundles = array();
|
||||
|
||||
$view = $this->settings['view']['view_name'];
|
||||
if ($view) {
|
||||
$view = views_get_view($view);
|
||||
$view->set_display($this->settings['view']['view_display']);
|
||||
|
||||
$handler = $view->display_handler->get_handler('filter', 'type');
|
||||
if ($handler) {
|
||||
$bundles = $handler->value;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$bundles = array_filter($this->settings['referenceable_types']);
|
||||
}
|
||||
|
||||
return ($bundles ? $bundles : parent::getTargetBundles());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CER plugin for Taxonomy Term Reference fields.
|
||||
*/
|
||||
|
||||
class CerTaxonomyTermReferenceField extends CerField {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return 'taxonomy_term';
|
||||
}
|
||||
|
||||
/**
|
||||
* @override CerField::getTargetBundles().
|
||||
*/
|
||||
public function getTargetBundles() {
|
||||
$bundles = array();
|
||||
|
||||
foreach ($this->settings['allowed_values'] as $item) {
|
||||
$bundles[] = $item['vocabulary'];
|
||||
}
|
||||
|
||||
return $bundles;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains the CER plugin for User Reference fields.
|
||||
*/
|
||||
|
||||
class CerUserReferenceField extends CerField {
|
||||
|
||||
/**
|
||||
* Implements CerField::getTargetType().
|
||||
*/
|
||||
public function getTargetType() {
|
||||
return 'user';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
class CerBasicTestCase extends DrupalWebTestCase {
|
||||
|
||||
/**
|
||||
* A user account under which the tests will be conducted.
|
||||
*
|
||||
* @var StdClass
|
||||
*/
|
||||
protected $author;
|
||||
|
||||
/**
|
||||
* A node that references $this->author.
|
||||
*
|
||||
* @var StdClass
|
||||
*/
|
||||
protected $node;
|
||||
|
||||
public static function getInfo() {
|
||||
return array(
|
||||
'name' => 'Basic',
|
||||
'description' => "Tests CER's basic CRUD functionality.",
|
||||
'group' => 'CER',
|
||||
);
|
||||
}
|
||||
|
||||
public function setUp() {
|
||||
// Turns out you have to enable your own module in the friggin' test, if
|
||||
// you want your own classes to be available. Lawsy me and other such
|
||||
// utterances...SimpleTest is teh suck.
|
||||
parent::setUp('entity', 'ctools', 'entityreference', 'field_object', 'cer');
|
||||
|
||||
$field = array(
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => 1,
|
||||
'field_name' => 'field_author',
|
||||
'settings' => array(
|
||||
'target_type' => 'user',
|
||||
),
|
||||
);
|
||||
field_create_field($field);
|
||||
|
||||
$instance = array(
|
||||
'field_name' => $field['field_name'],
|
||||
'entity_type' => 'node',
|
||||
'bundle' => 'page',
|
||||
);
|
||||
field_create_instance($instance);
|
||||
|
||||
$field = array(
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => FIELD_CARDINALITY_UNLIMITED,
|
||||
'field_name' => 'field_pages',
|
||||
'settings' => array(
|
||||
'target_type' => 'node',
|
||||
),
|
||||
'handler_settings' => array(
|
||||
'target_bundles' => array('page'),
|
||||
),
|
||||
);
|
||||
field_create_field($field);
|
||||
|
||||
$instance = array(
|
||||
'field_name' => $field['field_name'],
|
||||
'entity_type' => 'user',
|
||||
'bundle' => 'user',
|
||||
);
|
||||
field_create_instance($instance);
|
||||
|
||||
/** @var CerPreset $preset */
|
||||
$preset = entity_create('cer', array());
|
||||
$preset->wrapper->cer_left->set('node:page:field_author');
|
||||
$preset->wrapper->cer_right->set('user:user:field_pages');
|
||||
$preset->wrapper->cer_bidirectional->set(TRUE);
|
||||
$preset->wrapper->cer_enabled->set(TRUE);
|
||||
$preset->save();
|
||||
|
||||
$this->author = $this->drupalCreateUser();
|
||||
|
||||
$this->node = $this->drupalCreateNode(array(
|
||||
'field_author' => array(
|
||||
LANGUAGE_NONE => array(
|
||||
array('target_id' => $this->author->uid),
|
||||
),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
public function testCreate() {
|
||||
$author = $this->reload('user', $this->author);
|
||||
$this->assertEqual(1, $author->field_pages->count());
|
||||
$this->assertEqual($this->node->nid, $author->field_pages[0]->nid->value());
|
||||
}
|
||||
|
||||
public function testUpdateDereference() {
|
||||
// Dereference the node from the user.
|
||||
$this->author->field_pages = array();
|
||||
user_save($this->author);
|
||||
|
||||
// Reload $this->node from the database so we get the latest field values.
|
||||
$this->assertNull($this->reload('node', $this->node)->field_author->value());
|
||||
}
|
||||
|
||||
public function testUpdateChangeTarget() {
|
||||
$target = $this->drupalCreateUser();
|
||||
|
||||
$this->node->field_author[LANGUAGE_NONE][0]['target_id'] = $target->uid;
|
||||
node_save($this->node);
|
||||
|
||||
// The original author should no longer reference the node.
|
||||
$this->assertEqual(0, $this->reload('user', $this->author)->field_pages->count());
|
||||
|
||||
/** @var EntityDrupalWrapper $target */
|
||||
$target = $this->reload('user', $target);
|
||||
$this->assertEqual(1, $target->field_pages->count());
|
||||
$this->assertEqual($this->node->nid, $target->field_pages[0]->nid->value());
|
||||
}
|
||||
|
||||
public function testDelete() {
|
||||
node_delete($this->node->nid);
|
||||
$this->assertEqual(0, $this->reload('user', $this->author)->field_pages->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return EntityDrupalWrapper
|
||||
*/
|
||||
protected function reload($entity_type, $entity) {
|
||||
list ($id) = entity_extract_IDs($entity_type, $entity);
|
||||
$entities = entity_load($entity_type, array($id), NULL, TRUE);
|
||||
|
||||
return entity_metadata_wrapper($entity_type, $entities[$id]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
name = "CER Tests"
|
||||
core = "7.x"
|
||||
description = "Automated tests for CER."
|
||||
hidden = TRUE
|
||||
|
||||
dependencies[] = simpletest
|
||||
dependencies[] = cer
|
||||
|
||||
files[] = crud.test
|
||||
files[] = fields.test
|
||||
; Information added by Drupal.org packaging script on 2014-08-08
|
||||
version = "7.x-2.x-dev"
|
||||
core = "7.x"
|
||||
project = "cer"
|
||||
datestamp = "1407528862"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<?php
|
||||
@@ -1,168 +0,0 @@
|
||||
<?php
|
||||
|
||||
class CerCrudTest extends DrupalWebTestCase {
|
||||
|
||||
public static function getInfo() {
|
||||
return array(
|
||||
'name' => 'CRUD',
|
||||
'group' => 'Corresponding Entity Reference',
|
||||
'description' => 'Tests basic CER functionality.',
|
||||
);
|
||||
}
|
||||
|
||||
public function setUp() {
|
||||
parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
|
||||
|
||||
field_create_field(array(
|
||||
'field_name' => 'field_user',
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => -1,
|
||||
'settings' => array(
|
||||
'target_type' => 'user',
|
||||
),
|
||||
));
|
||||
field_create_field(array(
|
||||
'field_name' => 'field_node',
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => -1,
|
||||
'settings' => array(
|
||||
'target_type' => 'node',
|
||||
),
|
||||
));
|
||||
|
||||
field_create_instance(array(
|
||||
'field_name' => 'field_user',
|
||||
'entity_type' => 'node',
|
||||
'bundle' => 'page',
|
||||
));
|
||||
field_create_instance(array(
|
||||
'field_name' => 'field_node',
|
||||
'entity_type' => 'user',
|
||||
'bundle' => 'user',
|
||||
));
|
||||
|
||||
db_insert('cer')->fields(array(
|
||||
'entity_types_content_fields' => 'node*page*field_user*user*user*field_node',
|
||||
'enabled' => TRUE,
|
||||
))->execute();
|
||||
}
|
||||
|
||||
public function testImplicitReferenceCreation() {
|
||||
$uid = $this->drupalCreateUser()->uid;
|
||||
|
||||
$referrers = array();
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$referrers[] = $this->drupalCreateNode(array(
|
||||
'type' => 'page',
|
||||
'field_user' => array(
|
||||
'und' => array(
|
||||
array('target_id' => $uid),
|
||||
),
|
||||
),
|
||||
))->nid;
|
||||
}
|
||||
|
||||
$references = array();
|
||||
foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
|
||||
$references[] = $reference['target_id'];
|
||||
}
|
||||
$this->assertFalse(array_diff($referrers, $references), 'Creating 5 referrers to a single entity creates 5 corresponding references on that entity.', 'CER');
|
||||
}
|
||||
|
||||
public function testDuplicateReferencePrevention() {
|
||||
$uid = $this->drupalCreateUser()->uid;
|
||||
|
||||
$this->drupalCreateNode(array(
|
||||
'type' => 'page',
|
||||
'field_user' => array(
|
||||
'und' => array(
|
||||
array('target_id' => $uid),
|
||||
array('target_id' => $uid),
|
||||
),
|
||||
),
|
||||
));
|
||||
|
||||
$account = user_load($uid, TRUE);
|
||||
$this->assertEqual(sizeof($account->field_node['und']), 1, 'Creating two references to an entity from a single referrer creates one corresponding reference.', 'CER');
|
||||
}
|
||||
|
||||
public function testExplicitReferenceCreation() {
|
||||
$uid = $this->drupalCreateNode()->uid;
|
||||
|
||||
$node = $this->drupalCreateNode(array('type' => 'page'));
|
||||
$node->field_user['und'][0]['target_id'] = $uid;
|
||||
node_save($node);
|
||||
|
||||
$account = user_load($uid, TRUE);
|
||||
$this->assertEqual($account->field_node['und'][0]['target_id'], $node->nid, 'Creating an explicit reference between to unrelated entities creates a corresponding reference.', 'CER');
|
||||
}
|
||||
|
||||
public function testExplicitDereference() {
|
||||
$uid = $this->drupalCreateUser()->uid;
|
||||
|
||||
$nid = $this->drupalCreateNode(array(
|
||||
'type' => 'page',
|
||||
'field_user' => array(
|
||||
'und' => array(
|
||||
array('target_id' => $uid),
|
||||
),
|
||||
),
|
||||
))->nid;
|
||||
|
||||
$account = user_load($uid, TRUE);
|
||||
$account->field_node = array();
|
||||
user_save($account);
|
||||
|
||||
$node = node_load($nid, NULL, TRUE);
|
||||
$this->assertFalse($node->field_user, 'Explicitly clearing a reference from the referenced entity clears the corresponding reference on the referrer.', 'CER');
|
||||
}
|
||||
|
||||
public function testReferrerDeletion() {
|
||||
$uid = $this->drupalCreateUser()->uid;
|
||||
|
||||
$referrers = array();
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$referrers[] = $this->drupalCreateNode(array(
|
||||
'type' => 'page',
|
||||
'field_user' => array(
|
||||
'und' => array(
|
||||
array('target_id' => $uid),
|
||||
),
|
||||
),
|
||||
))->nid;
|
||||
}
|
||||
|
||||
node_delete($referrers[0]);
|
||||
|
||||
$references = array();
|
||||
foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
|
||||
$references[] = $reference['target_id'];
|
||||
}
|
||||
$this->assertFalse(in_array($referrers[0], $references), 'Deleting a referrer clears corresponding reference on the referenced entity.', 'CER');
|
||||
}
|
||||
|
||||
public function testReferencedEntityDeletion() {
|
||||
$uid = $this->drupalCreateUser()->uid;
|
||||
|
||||
$referrers = array();
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$referrers[] = $this->drupalCreateNode(array(
|
||||
'type' => 'page',
|
||||
'field_user' => array(
|
||||
'und' => array(
|
||||
array('target_id' => $uid),
|
||||
),
|
||||
),
|
||||
))->nid;
|
||||
}
|
||||
user_delete($uid);
|
||||
|
||||
$cleared = 0;
|
||||
foreach ($referrers as $nid) {
|
||||
$node = node_load($nid, NULL, TRUE);
|
||||
$cleared += (int) empty($node->field_user);
|
||||
}
|
||||
$this->assertEqual($cleared, sizeof($referrers), 'Deleting a referenced entity clears all references to it.', 'CER');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
<?php
|
||||
|
||||
class CerFieldTestCase extends DrupalWebTestCase {
|
||||
|
||||
public static function getInfo() {
|
||||
return array(
|
||||
'name' => 'Fields',
|
||||
'group' => 'Corresponding Entity Reference',
|
||||
'description' => 'Tests integration with the Field API.',
|
||||
);
|
||||
}
|
||||
|
||||
public function setUp() {
|
||||
parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
|
||||
|
||||
field_create_field(array(
|
||||
'field_name' => 'field_user',
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => -1,
|
||||
'settings' => array(
|
||||
'target_type' => 'user',
|
||||
),
|
||||
));
|
||||
field_create_field(array(
|
||||
'field_name' => 'field_node',
|
||||
'type' => 'entityreference',
|
||||
'cardinality' => -1,
|
||||
'settings' => array(
|
||||
'target_type' => 'node',
|
||||
),
|
||||
));
|
||||
|
||||
field_create_instance(array(
|
||||
'field_name' => 'field_user',
|
||||
'entity_type' => 'node',
|
||||
'bundle' => 'page',
|
||||
));
|
||||
field_create_instance(array(
|
||||
'field_name' => 'field_node',
|
||||
'entity_type' => 'user',
|
||||
'bundle' => 'user',
|
||||
));
|
||||
|
||||
ctools_include('export');
|
||||
|
||||
$preset = ctools_export_crud_new('cer');
|
||||
$preset->entity_types_content_fields = 'node*page*field_user*user*user*field_node';
|
||||
$preset->enabled = TRUE;
|
||||
|
||||
ctools_export_crud_save('cer', $preset);
|
||||
}
|
||||
|
||||
public function testFieldInstanceDelete() {
|
||||
field_delete_instance(field_info_instance('user', 'field_node', 'user'));
|
||||
|
||||
$preset = cer_preset_load('node*page*field_user*user*user*field_node');
|
||||
$this->assertNull($preset, 'Deleting a field instance clears CER presets for that instance.');
|
||||
}
|
||||
|
||||
public function testFieldDelete() {
|
||||
field_delete_field('field_user');
|
||||
|
||||
$preset = cer_preset_load('node*page*field_user*user*user*field_node');
|
||||
$this->assertNull($preset, 'Deleting a field clears CER presets for that field.');
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user