Created
March 11, 2016 15:59
-
-
Save filipengberg/ed4be390163ed18bd279 to your computer and use it in GitHub Desktop.
Drupal 8 EventSubscriber that sets the category field based on entity browser id
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Contains \Drupal\image_library\EventSubscriber. | |
*/ | |
namespace Drupal\image_library\EventSubscriber; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\EventDispatcher\Event; | |
use Drupal\entity_browser\Events\Events; | |
use Drupal\entity_browser\Events\EntitySelectionEvent; | |
/** | |
* Class EventSubscriber. | |
* | |
* @package Drupal\image_library | |
*/ | |
class EventSubscriber implements EventSubscriberInterface { | |
private $browser_prefix = 'image_library_browser'; | |
private $vocabolary = 'image_categories'; | |
/** | |
* {@inheritdoc} | |
*/ | |
static function getSubscribedEvents() { | |
$events[Events::SELECTED][] = array('onSelected'); | |
return $events; | |
} | |
/** | |
* Set image category to image fields based on entity browser id | |
* uses the following convention for browser id to figure out target category | |
* browser id: media_library_browser__{{term_name}} | |
*/ | |
public function onSelected(EntitySelectionEvent $event) { | |
$browser = $event->getBrowserID(); | |
// Ignore if we are not dealing with a media library browser | |
if (strpos($browser, $this->browser_prefix) === false) { | |
return; | |
} | |
// Figure out target category from browser id | |
$category = str_replace($this->browser_prefix . '__', '', $browser); | |
if (empty($category)) { | |
continue; | |
} | |
// Only act on entities that has no image category set | |
$uncategorized = array_filter($event->getEntities(), function ($entity) { | |
return !isset($entity->field_category->entity); | |
}); | |
// Loop through image entities and set categories | |
foreach($uncategorized as $entity) { | |
// Get target tid from category | |
$terms = taxonomy_term_load_multiple_by_name($category, $this->vocabolary); | |
if (empty($terms)) { | |
continue; | |
} | |
// Get first matched term tid | |
$tid = reset(array_keys($terms)); | |
// Save tid on entity | |
$entity->field_category->target_id = $tid; | |
$entity->save(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment