Chutier link from audio player cartel is working git add .

This commit is contained in:
Bachir Soussi Chiadmi
2018-03-11 18:44:32 +01:00
parent 12a4b7c6a9
commit c0d185bb6d
23 changed files with 667 additions and 197 deletions
@@ -1,5 +1,63 @@
(function ($, Drupal) {
function init(){
console.log('Studio Init');
initEvents();
initAjax();
};
function initEvents(){
$('body').on('new-audio-cartel-loaded', initAjax);
};
function initAjax(){
console.log('studio initAjax chutier');
$('.chutier-ajax-link:not(.ajax-enabled)')
.addClass('ajax-enabled')
.on('click', onClickAjaxLink);
};
function onClickAjaxLink(e){
console.log('studio onClickAjaxLink chutier');
e.preventDefault();
// var $this = $(this);
addRemoveToChutier($(this));
// switch($this.attr('action')){
// case 'add':
// // TODO: get target chutier
// addToChutier($this);
// break;
// case 'remove':
// // TODO: if we use more than one chutoer per user get target chutier
// removeFromChutier($this);
// break;
// }
return false;
};
function addRemoveToChutier($link){
// var ajax_path = 'edlp_studio/ajax/chutier/add/'+id; // + '/' +cid;
var ajax_path = $link.attr('data-drupal-link-system-path');
var path = window.location.origin + drupalSettings.path.baseUrl + ajax_path;
$link.addClass('ajax-loading');
$.getJSON(path, {})
.done(function(data){
onActionToChutierDone($link, data);
})
.fail(function(jqxhr, textStatus, error){
onErrorActionToChutier(jqxhr, textStatus, error, $link);
});
};
function onActionToChutierDone($link, data){
console.log('onActionToChutierDone',data);
$link.replaceWith(data.new_link);
initAjax();
};
function onErrorActionToChutier(jqxhr, textStatus, error, $link){
console.warn('add to chuttier load failed : '+error, jqxhr.responseText);
};
init();
})(jQuery, Drupal);
@@ -1,3 +1,6 @@
edlp_studio-library:
js:
js/edlp_studio.js: {}
assets/js/edlp_studio.js: { scope: footer }
dependencies:
- core/drupalSettings
- core/jquery
@@ -6,7 +6,8 @@
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\edlp_studio\Entity\Chutier;
/**
* Implements hook_help().
*/
@@ -23,6 +24,15 @@ function edlp_studio_help($route_name, RouteMatchInterface $route_match) {
}
}
/**
* Implements hook_page_attachments().
* @param array $attachments
*/
function edlp_studio_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'edlp_studio/edlp_studio-library';
}
/**
* hook_entity_extra_field_info()
*
@@ -30,8 +40,8 @@ function edlp_studio_help($route_name, RouteMatchInterface $route_match) {
function edlp_studio_entity_extra_field_info(){
$extra = [];
// TODO: get node content type by settings @see readme
$extra['node']['enregistrement']['display']['add_to_chutier'] = [
'label' => t('Add to chutier link'),
$extra['node']['enregistrement']['display']['chutier_actions'] = [
'label' => t('Chutier actions'),
'description' => 'Display a link to add the content to chutier',
'weight' => 99,
'visible' => FALSE,
@@ -45,18 +55,41 @@ function edlp_studio_entity_extra_field_info(){
* @see https://www.amazeelabs.com/en/render-menu-tree-custom-code-drupal-8
*/
function edlp_studio_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
$display_settings = $display->getComponent('add_to_chutier');
$display_settings = $display->getComponent('chutier_actions');
if (!empty($display_settings)) {
// dpm($entity);
// dpm($entity->id());
$url = Url::fromRoute('edlp_studio.chutier_controller_add_content', ['id'=>$entity->id()], array(
'attributes' => array(
'class' => ['add-to-chutier-link', 'ajax-link'],
'target_id' => $entity->id(),
)
));
$build['add_to_chutier'] = array(
'#title' => t("Add this content to chutier."),
$user = \Drupal::currentUser();
// dpm($user);
if($user->id() == 0){
// // TODO: check if user loged in ? yes -> links : no : popup message
// $action = 'add';
}
// else{
// // TODO: check if node already in chutier ? no -> add link : yes -> remove link
// // use getUserChutiersContents() from \Drupal\edlp_studio\ChutierInterface
// $contents = Chutier::getUserChutiersContents($user->id());
// dpm($contents);
// if(array_search($entity->id(), $contents) === false){
// $action = 'add';
// }else{
// $action = 'remove';
// }
// }
// $args = array(
// 'action'=>$action,
// 'id'=>$entity->id()
// );
// $url = Url::fromRoute('edlp_studio.chutier_controller_ajax_add_content', $args, array(
// 'attributes' => array(
// 'class' => ['chutier-link','chutier-ajax-link'],
// 'action' => $action,
// 'target_id' => $entity->id(),
// )
// ));
$url = Chutier::getActionsUrl($entity->id(), $user->id());
$build['chutier_actions'] = array(
'#title' => t("Chutier."),
'#type' => 'link',
'#url' => $url,
'#options'=>array(
@@ -6,10 +6,11 @@ edlp_studio.studio:
requirements:
_permission: 'administer studio'
edlp_studio.chutier_controller_add_content:
path: '/studio/chutier/add/{id}'
edlp_studio.chutier_controller_ajax_add_content:
path: '/edlp_studio/ajax/chutier/{action}/{id}/{cid}'
defaults:
_controller: '\Drupal\edlp_studio\Controller\ChutierController::addContent'
_title: 'Add content to chutier'
_controller: '\Drupal\edlp_studio\Controller\ChutierController::AddRemoveContent'
_title: 'Add/remove content to/from chutier'
cid: null
requirements:
_permission: 'use chutier'
@@ -20,6 +20,8 @@ class ChutierListBuilder extends EntityListBuilder {
public function buildHeader() {
$header['id'] = $this->t('Chutier ID');
$header['name'] = $this->t('Name');
$header['user'] = $this->t('User');
// $header['default'] = $this->t('User id');
return $header + parent::buildHeader();
}
@@ -34,6 +36,13 @@ class ChutierListBuilder extends EntityListBuilder {
'entity.chutier.edit_form',
['chutier' => $entity->id()]
);
$row['user'] = Link::createFromRoute(
$entity->getOwner()->getUserName(),
'entity.user.canonical',
['user' => $entity->getOwnerId()]
);
// $row['uid'] = $entity->getOwnerId();
return $row + parent::buildRow($entity);
}
@@ -3,38 +3,173 @@
namespace Drupal\edlp_studio\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\User\UserDataInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\edlp_studio\Entity\Chutier;
/**
* Class ChutierController.
*/
class ChutierController extends ControllerBase {
protected $user;
protected $userdata;
/**
* Hello.
* Class constructor.
*/
public function __construct(AccountInterface $account, UserDataInterface $userdata) {
$this->user = $account;
$this->userdata = $userdata;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
// Instantiates this form class.
return new static(
// Load the service required to construct this class.
$container->get('current_user'),
$container->get('user.data')
);
}
/**
* AdddContent.
*
* @return json
* Return Hello string.
* Return status.
*/
public function AddContent($id) {
// TODO: get current user
// TODO: check if default chutier exists ? yes use it : no create and use it.
// TODO: add $id to documents field
// TODO: return status
public function AddRemoveContent($action, $id, $cid) {
$this->error_message = null;
$status = 'ok';
// get current user :
// done by DependencyInjection of AccountInterface
$response = new JsonResponse();
// TODO: use the send chutier instead of default
// check if default chutier exists ? yes use it : no create and use it.
$this->checkChutier();
// dpm($this->chutier);
$data = array(
'test' => 'Hello chutier',
// check if $id exists, is a document, and does not already exist in chutier
switch($action){
case 'add':
$this->validateNewDoc($id);
if(!$this->error_message){
// add $id to documents field
$this->addNewDoc($id);
$message = t('Node @id added to chutier.', array('@id'=>$id));
}else{
$status = "error";
}
break;
case 'remove':
$this->removeDoc($id);
$message = t('Node @id removed to chutier.', array('@id'=>$id));
break;
}
$url = Chutier::getActionsUrl($id, $this->user->id());
$new_link_build = array(
'#title' => t("Chutier."),
'#type' => 'link',
'#url' => $url,
'#options'=>array(
'attributes' => array(
'data-drupal-link-system-path' => $url->getInternalPath()
)
)
);
$new_link = render($new_link_build);
if($status == 'error'){
$message = $this->error_message;
}
// JSON
$response = new JsonResponse();
$data = array(
'status' => $status,
'message' => $message,
'new_link' => $new_link,
);
$response->setData($data);
return $response;
// classic html
// return array(
// '#markup'=>'Hello Chutier'
// ); }
// '#markup'=>'Status : ' . $status . ' | Message : ' . $message,
// );
}
private function addNewDoc($id){
$this->chutier->documents->appendItem($id);
$this->chutier->save();
}
private function removeDoc($id){
$values = array_column($this->chutier->documents->getValue(), 'target_id');
$index = array_search($id,$values);
$this->chutier->documents->removeItem($index);
$this->chutier->save();
}
private function validateNewDoc($id){
$node = entity_load('node', $id);
if($node){
// TODO: get node bundle by settings (@see readme)
if($node->getType() == 'enregistrement'){
$docs = array_column($this->chutier->documents->getValue(), 'target_id');
if( in_array($id, $docs) ){
$this->error_message = t("Node '@title'(@id) already exists in chutier '@name'(@cid)", array(
'@title'=>$node->getTitle(),
'@id'=>$id,
'@name' => $this->chutier->getName(),
'@cid' => $this->chutier->id())
);
}
}else{
$this->error_message = t("Node @title (@id) is not an Enregistrement (@type)", array(
'@title'=>$node->getTitle(),
'@id'=>$id,
'@type' => $node->getType())
);
}
}else{
$this->error_message = t("Node @id does not exists", array('@id'=>$id));
}
}
private function checkChutier(){
$default_chutier_id = $this->userdata->get('edlp_studio', $this->user->id(), 'default_chutier');
// dpm($this->default_chutier_id);
$this->chutier = entity_load('chutier', $default_chutier_id);
// if default chutier does not exists, create, save and record it
if(!$this->chutier){
$this->createDefaultChutier();
}
}
private function createDefaultChutier(){
// dpm('createDefaultChutier');
$this->createChutier();
$this->userdata->set('edlp_studio', $this->user->id(), 'default_chutier', $this->chutier->id());
}
public function createChutier(){
$chutier = array(
'id' => NULL,
'uid' => $this->user->id(),
'status' => TRUE,
'name' => t('Default'),
);
$this->chutier = entity_create('chutier', $chutier);
$this->chutier->save();
}
}
@@ -8,6 +8,7 @@ use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Url;
/**
* Defines the Chutier entity.
@@ -240,4 +241,55 @@ class Chutier extends ContentEntityBase implements ChutierInterface {
return $fields;
}
/**
* {@inheritdoc}
*/
public static function getUserChutiersContents($uid){
// TODO: use query if we use more than one chutier
// $query = \Drupal::entityQuery('chutier')
// ->condition('user_id', $uid);
//
// $chutiers_nids = $query->execute();
// $chutiers = entity_load_multiple('chutier', $chutiers_nids);
//
// $contents = array();
// foreach ($chutiers as $id => $chutier) {
// $contents[$id] = array_column($chutier->documents->getValue(), 'target_id');
// }
/** @var UserDataInterface $userData */
$userData = \Drupal::service('user.data');
$default_chutier_id = $userData->get('edlp_studio', $uid, 'default_chutier');
if($chutier = entity_load('chutier', $default_chutier_id)){
return array_column($chutier->documents->getValue(), 'target_id');
}else{
return array();
}
}
/**
* {@inheritdoc}
*/
public static function getActionsUrl($id, $uid){
$contents = self::getUserChutiersContents($uid);
// dpm($contents);
if(array_search($id, $contents) === false){
$action = 'add';
}else{
$action = 'remove';
}
$args = array(
'action'=>$action,
'id'=>$id
);
$url = Url::fromRoute('edlp_studio.chutier_controller_ajax_add_content', $args, array(
'attributes' => array(
'class' => ['chutier-link','chutier-ajax-link'],
'action' => $action,
'target_id' => $id,
)
));
return $url;
}
}
@@ -74,4 +74,33 @@ interface ChutierInterface extends ContentEntityInterface, EntityChangedInterfac
*/
public function setPublished($published);
/**
* get the contents in user's chutiers
*
* @param int $uid
* user id
*
* @return array
* associative array of contents by chutiers
*
*/
public static function getUserChutiersContents($uid);
/**
* get the contents in user's chutiers
*
* @param int $id
* content id
*
* @param int $uid
* user id
*
* @return Drupal\Core\Url
* depending on action is add or remove
*
*/
public static function getActionsURL($id, $uid);
}