4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 namespace Civi\Api4\Generic
;
25 * Base class for all `Save` api actions.
27 * @method $this setRecords(array $records) Set array of records to be saved.
28 * @method array getRecords()
29 * @method $this setDefaults(array $defaults) Array of defaults.
30 * @method array getDefaults()
31 * @method $this setReload(bool $reload) Specify whether complete objects will be returned after saving.
32 * @method bool getReload()
34 * @package Civi\Api4\Generic
36 abstract class AbstractSaveAction
extends AbstractAction
{
39 * Array of $ENTITIES to save.
41 * Should be in the same format as returned by `Get`.
46 protected $records = [];
49 * Array of default values.
51 * These defaults will be merged into every $ENTITY in `records` before saving.
52 * Values set in `records` will override these defaults if set in both places,
53 * but updating existing $ENTITIES will overwrite current values with these defaults.
57 protected $defaults = [];
60 * Reload $ENTITIES after saving.
62 * By default this action typically returns partial records containing only the fields
63 * that were updated. Set `reload` to `true` to do an additional lookup after saving
64 * to return complete values for every $ENTITY.
68 protected $reload = FALSE;
76 * BatchAction constructor.
77 * @param string $entityName
78 * @param string $actionName
79 * @param string $idField
81 public function __construct($entityName, $actionName, $idField = 'id') {
82 // $idField should be a string but some apis (e.g. CustomValue) give us an array
83 $this->idField
= array_values((array) $idField)[0];
84 parent
::__construct($entityName, $actionName);
88 * @throws \API_Exception
90 protected function validateValues() {
92 foreach ($this->records
as $record) {
93 if (empty($record[$this->idField
])) {
94 $unmatched = array_unique(array_merge($unmatched, $this->checkRequiredFields($record)));
98 throw new \
API_Exception("Mandatory values missing from Api4 {$this->getEntityName()}::{$this->getActionName()}: " . implode(", ", $unmatched), "mandatory_missing", ["fields" => $unmatched]);
105 protected function getIdField() {
106 return $this->idField
;
110 * Add one or more records to be saved.
111 * @param array ...$records
114 public function addRecord(array ...$records) {
115 $this->records
= array_merge($this->records
, $records);
120 * Set default value for a field.
121 * @param string $fieldName
122 * @param mixed $defaultValue
125 public function addDefault(string $fieldName, $defaultValue) {
126 $this->defaults
[$fieldName] = $defaultValue;