toolbar_plus-1.0.x-dev/src/LoadEditablePageResponseTrait.php
src/LoadEditablePageResponseTrait.php
<?php
namespace Drupal\toolbar_plus;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\EntityInterface;
trait LoadEditablePageResponseTrait {
/**
* Get empty content.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param string $view_mode
* The view mode.
*
* @return array
* A wrapped empty item that content can be added to.
*/
public function getEmptyContent(EntityInterface $entity, string $view_mode) {
$content['#type'] = 'item';
$content['#wrapper_attributes']['data-toolbar-plus-entity-wrapper'] = $this->getWrapperId($entity, $view_mode);
return $content;
}
/**
* Get Ajax replace response.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param string $view_mode
* The view mode.
* @param array $content
* The content to replace into the page.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* An AJAX response to swap out the entity on the page with the given content.
*/
public function getAjaxReplaceResponse(EntityInterface $entity, string $view_mode, array $content) {
$content['#cache']['contexts'][] = 'cookies:editMode';
$response = new AjaxResponse();
$selector = "[data-toolbar-plus-entity-wrapper='" . $this->getWrapperId($entity) . "'][data-toolbar-plus-view-mode='$view_mode']";
$response->addCommand(new ReplaceCommand($selector, $content));
return $response;
}
/**
* Get wrapper ID.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
* @param string $view_mode
* The view mode.
*
* @return string
* The wrapper ID.
*/
private function getWrapperId(EntityInterface $entity) {
return sprintf('%s::%s::%s', $entity->getEntityTypeId(), edit_plus_entity_identifier($entity), $entity->bundle());
}
}
