- Модуль: crm
- Путь к файлу: ~/bitrix/modules/crm/lib/item/fieldimplementation/binding.php
- Класс: Bitrix\Crm\Item\FieldImplementation\Binding
- Вызов: Binding::save
public function save(): Result
{
if (is_null($this->boundEntity) || empty($this->thisIdField))
{
// everything was saved at entityObject save
return new Result();
}
$newBindings = $this->get($this->fieldNameMap->getBindings());
$boundIdsAfterSave = EntityBinding::prepareEntityIDs($this->boundEntityTypeId, $newBindings);
sort($this->boundIdsBeforeSave);
sort($boundIdsAfterSave);
if ($boundIdsAfterSave === $this->boundIdsBeforeSave)
{
return new Result();
}
$affectedIds = array_unique(array_merge($this->boundIdsBeforeSave, $boundIdsAfterSave));
if (empty($affectedIds))
{
return new Result();
}
$query = new Query($this->bindingEntity);
/** @var Collection $collection */
$collection =
$query
->setSelect([$this->boundEntityIdFieldName, $this->thisIdField, 'IS_PRIMARY'])
->whereIn($this->boundEntityIdFieldName, $affectedIds)
->fetchCollection()
;
/** @var Array $newPrimaryMap */
$newPrimaryMap = [];
foreach ($collection as $object)
{
$boundEntityId = $object->require($this->boundEntityIdFieldName);
$thisId = $object->require($this->thisIdField);
$isPrimary = $object->require('IS_PRIMARY');
$primaryDesc = $newPrimaryMap[$boundEntityId] ?? null;
if (
is_null($primaryDesc)
|| $isPrimary && $primaryDesc['isPrimary'] === false
|| $thisId < $primaryDesc['thisId'] && !$primaryDesc['isPrimary']
)
{
$newPrimaryMap[$boundEntityId] = ['isPrimary' => $isPrimary, 'thisId' => $thisId];
}
}
foreach ($affectedIds as $affectedId)
{
if (!isset($newPrimaryMap[$affectedId]))
{
//no primary found - set to null
$newPrimaryMap[$affectedId] = ['isPrimary' => false, 'thisId' => null];
}
}
$result = new Result();
foreach ($newPrimaryMap as $boundEntityId => $primaryDesc)
{
$updateResult = $this->boundEntity->getDataClass()::update(
$boundEntityId,
['fields' => [$this->thisIdField => $primaryDesc['thisId']]],
);
if (!$updateResult->isSuccess())
{
$result->addErrors($updateResult->getErrors());
}
}
return $result;
}