Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flexible primary logic 2 #31

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/EntityManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public function delete()

$model = $this->modelClass;

$result = $model::delete($this->itemId); // удаляем основную сущность
$result = $model::delete($this->helper->getPk()); // удаляем основную сущность
if(!$result->isSuccess()){ // если не удалилась
$db->rollbackTransaction(); // то восстанавливаем зависимые сущности
return $result; // возвращаем ошибку
Expand Down
21 changes: 21 additions & 0 deletions lib/helper/AdminBaseHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Bitrix\Main\LoaderException;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\ModuleManager;
use DigitalWand\AdminHelper\EntityManager;
use DigitalWand\AdminHelper\Widget\HelperWidget;
use Bitrix\Main\Entity\DataManager;
use Bitrix\Highloadblock as HL;
Expand Down Expand Up @@ -108,6 +109,15 @@ abstract class AdminBaseHelper
*/
static protected $model;

/**
* @var string
* Имя класса используемого менеджера сущностей. Используется для выполнения CRUD-операций.
*
* @see DataManager
* @api
*/
static protected $entityManager = '\DigitalWand\AdminHelper\EntityManager';

/**
* @var string
* Назвние модуля данной модели.
Expand Down Expand Up @@ -598,6 +608,17 @@ public function pk()
return 'ID';
}

/**
* Возвращает значение первичного ключа таблицы используемой модели
* @return array|int|null
*
* @api
*/
public function getPk()
{
return isset($_REQUEST['FIELDS'][$this->pk()]) ? $_REQUEST['FIELDS'][$this->pk()] : $_REQUEST[$this->pk()];
}

/**
* Возвращает первичный ключ таблицы используемой модели разделов. Для HL-инфоблоков битрикс - всегда ID.
* Но может поменяться для какой-либо другой сущности.
Expand Down
19 changes: 9 additions & 10 deletions lib/helper/AdminEditHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public function __construct(array $fields, array $tabs = array())
if ($this->editAction()) {
if (isset($_REQUEST['apply'])) {
$id = $this->data[$this->pk()];
$url = $this->app->GetCurPageParam($this->pk() . '=' . $id);
$url = $this->app->GetCurPageParam($this->pk() . '=' . (is_array($id) ? $id[$this->pk()] : $id), array('ID'));
}
else {
if (isset($_REQUEST['save'])) {
Expand Down Expand Up @@ -430,7 +430,7 @@ protected function editAction()
if ($success) {
$this->setContext(AdminEditHelper::OP_EDIT_ACTION_AFTER);
$existing = false;
$id = isset($_REQUEST['FIELDS'][$this->pk()]) ? $_REQUEST['FIELDS'][$this->pk()] : $_REQUEST[$this->pk()];
$id = $this->getPk();

if ($id) {
/** @var DataManager $className */
Expand Down Expand Up @@ -487,9 +487,9 @@ protected function editAction()
*/
protected function loadElement($select = array())
{
if (isset($_REQUEST[$this->pk()])) {
if ($this->getPk() !== null) {
$className = static::getModel();
$result = $className::getById($_REQUEST[$this->pk()]);
$result = $className::getById($this->getPk());

return $result->fetch();
}
Expand All @@ -515,9 +515,8 @@ protected function loadElement($select = array())
*/
protected function saveElement($id = null)
{
$className = static::getModel();
$entityManager = new EntityManager($className, $this->data, $id, $this);

/** @var EntityManager $entityManager */
$entityManager = new static::$entityManager(static::getModel(), empty($this->data) ? array() : $this->data, $id, $this);
$saveResult = $entityManager->save();
$this->addNotes($entityManager->getNotes());

Expand All @@ -542,9 +541,9 @@ protected function deleteElement($id)

return false;
}

$className = static::getModel();
$entityManager = new EntityManager($className, array(), $id, $this);
/** @var EntityManager $entityManager */
$entityManager = new static::$entityManager(static::getModel(), empty($this->data) ? array() : $this->data, $id, $this);

$deleteResult = $entityManager->delete();
$this->addNotes($entityManager->getNotes());
Expand Down
49 changes: 35 additions & 14 deletions lib/helper/AdminListHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public function __construct(array $fields, $isPopup = false)
$this->prepareAdminVariables();

$className = static::getModel();
$oSort = new \CAdminSorting($this->getListTableID(), static::pk(), "desc");
$oSort = new \CAdminSorting($this->getListTableID(), $this->pk(), "desc");
$this->list = new \CAdminList($this->getListTableID(), $oSort);
$this->list->InitFilter($this->arFilterFields);

Expand Down Expand Up @@ -419,7 +419,7 @@ protected function getContextMenu()
$params = $this->additionalUrlParams;
$sectionModel = $sectionEditHelper::getModel();
$sectionField = $sectionEditHelper::getSectionField();
$section = $sectionModel::getById($_GET['ID'])->Fetch();
$section = $sectionModel::getById($this->getPk())->Fetch();
if ($this->isPopup()) {
$params = array_merge($_GET);
}
Expand Down Expand Up @@ -516,14 +516,15 @@ protected function groupActions($IDs, $action)
if ($sectionEditHelperClass) {
$sectionField = !isset($_REQUEST['model']) ? static::getSectionField() :
$sectionEditHelperClass::getSectionField();
$element = $className::getById($IDs[0])->Fetch();
$element = $className::getById($this->getPk())->Fetch();
if ($element[$sectionField]) {
$params['ID'] = $element[$sectionField];
}
}

foreach ($IDs as $id) {
$entityManager = new EntityManager($className, array(), $id, $this);
/** @var EntityManager $entityManager */
$entityManager = new static::$entityManager(static::getModel(), empty($this->data) ? array() : $this->data, $id, $this);
$result = $entityManager->delete();
$this->addNotes($entityManager->getNotes());
if(!$result->isSuccess()){
Expand All @@ -541,7 +542,7 @@ protected function groupActions($IDs, $action)

if ($action == 'delete-section') {
if ($this->hasDeleteRights()) {
$section = $sectionClassName::getById($IDs[0])->Fetch();
$section = $sectionClassName::getById($this->getPk())->Fetch();
$sectionField = $sectionEditHelperClass::getSectionField();
$params = $_GET;
unset($params['action']);
Expand All @@ -550,9 +551,9 @@ protected function groupActions($IDs, $action)
if ($section[$sectionField]) {
$params['ID'] = $section[$sectionField];
}
foreach ($IDs as $id) {
$sectionClassName::delete($id);
}

$sectionClassName::delete($this->getPk());

LocalRedirect($listHelperClass::getUrl($params));
}
else {
Expand Down Expand Up @@ -750,8 +751,8 @@ public function buildList($sort)
}

$className = static::getModel();
$visibleColumns[] = static::pk();
$sectionsVisibleColumns[] = static::sectionPk();
$visibleColumns[] = $this->pk();
$sectionsVisibleColumns[] = $this->sectionPk();

$raw = array(
'SELECT' => $visibleColumns,
Expand Down Expand Up @@ -988,7 +989,7 @@ protected function getMixedData($sectionsVisibleColumns, $elementVisibleColumns,
}
// добавляем к выборке разделы
$rsSections = $sectionModel::getList(array(
'filter' => $sectionFilter,
'filter' => $this->getSectionsFilter($sectionFilter),
'select' => $sectionsVisibleColumns,
'order' => $sectionSort,
'limit' => $limitData[1],
Expand Down Expand Up @@ -1033,7 +1034,7 @@ protected function getMixedData($sectionsVisibleColumns, $elementVisibleColumns,
}

$elementParams = array(
'filter' => $elementFilter,
'filter' => $this->getElementsFilter($elementFilter),
'select' => $elementVisibleColumns,
'order' => $elementSort,
);
Expand Down Expand Up @@ -1156,7 +1157,7 @@ protected function getRow($data, $class = false)
else {
$query = array_merge($this->additionalUrlParams, array(
'lang' => LANGUAGE_ID,
static::pk() => $data[static::pk()]
$this->pk() => $data[$this->pk()]
));

return array($class::getUrl($query));
Expand Down Expand Up @@ -1303,7 +1304,7 @@ protected function addRowCell($row, $code, $data, $virtualCode = false)
protected function getData($className, $filter, $select, $sort, $raw)
{
$parameters = array(
'filter' => $filter,
'filter' => $this->getElementsFilter($filter),
'select' => $select,
'order' => $sort
);
Expand Down Expand Up @@ -1435,4 +1436,24 @@ public static function getUrl(array $params = array())
{
return static::getViewURL(static::getViewName(), static::$listPageUrl, $params);
}

/**
* Кастомизация фильтра разделов
* @param $filter
* @return mixed
*/
protected function getSectionsFilter(array $filter)
{
return $filter;
}

/**
* Кастомизация фильтра элементов
* @param $filter
* @return mixed
*/
protected function getElementsFilter($filter)
{
return $filter;
}
}
6 changes: 3 additions & 3 deletions lib/widget/ComboBoxWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,14 @@ protected function getVariants()
{
$variants = $this->getSettings('VARIANTS');

if (is_array($variants) AND !empty($variants)) {
return $this->formatVariants($variants);
} elseif (is_callable($variants)) {
if (is_callable($variants)) {
$var = $variants();

if (is_array($var)) {
return $this->formatVariants($var);
}
}elseif (is_array($variants) AND !empty($variants)) {
return $this->formatVariants($variants);
}

return array();
Expand Down
3 changes: 1 addition & 2 deletions lib/widget/StringWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,7 @@ public function generateRow(&$row, $data)
if ($this->getSettings('MULTIPLE')) {
} else {
if ($this->getSettings('EDIT_LINK') || $this->getSettings('SECTION_LINK')) {
$entityClass = $this->entityName;
$pk = $entityClass::getEntity()->getPrimary();
$pk = $this->helper->pk();

if ($this->getSettings('SECTION_LINK')) {
$params = $this->helper->isPopup() ? $_GET : array();
Expand Down