-
Notifications
You must be signed in to change notification settings - Fork 173
9.1. Access unpublished nodes
Dane Rossenrode edited this page Apr 9, 2016
·
1 revision
To allow a node resource to access unpublished nodes, you will need to create a custom data provider. Following is some sample code that does this.
<?php
/**
* @file
* Contains \Drupal\my_module\Plugin\DataProvider\DataProviderNodeUnpublished.
*/
namespace Drupal\ my_module\Plugin\DataProvider;
use Drupal\restful\Exception\BadRequestException;
use Drupal\restful\Plugin\resource\DataProvider\DataProviderInterface;
use Drupal\restful\Plugin\resource\DataProvider\DataProviderNode;
class DataProviderNodeUnpublished extends DataProviderNode implements DataProviderInterface {
/**
* Overrides DataProviderEntity::getQueryForList().
*
* Expose both published and unpublished nodes. Filter out anon results
* though, because unpublished anon results would otherwise be accessible to
* all anon users.
*/
public function getQueryForList() {
$query = parent::getQueryForList();
$this->removePublishedCondition($query);
return $query;
}
/**
* Overrides DataProviderEntity::getQueryCount().
*
* Count both published and unpublished nodes.
*/
public function getQueryCount() {
$query = parent::getQueryCount();
$this->removePublishedCondition($query);
return $query;
}
/**
* Remove the "Published" status condition from the passed query, if it has one.
*
* @param dbQuery $query
* The query object.
* @return dbQuery
* The modified query object.
*/
private function removePublishedCondition($query) {
// The implementation is ugly, but seems Drupal offers nothing better:
foreach ($query->propertyConditions as $id => $condition) {
if ($condition['column'] === 'status') {
unset($query->propertyConditions[$id]);
}
}
}
}
Finally, your resource definition will need to implement the following method, and specify your new custom data provider.
eg
protected function dataProviderClassName() {
return '\Drupal\my_module\Plugin\DataProvider\DataProviderNodeUnpublished';
}