DeleteBehavior
API reference › Soft Delete › DeleteBehavior
Marks ActiveRecord models as deleted instead of removing their rows, and restores them from that state.
softDelete() writes $softDeleteAttributeValues, restore() writes the restore values, and
safeDelete() attempts a physical delete first and marks the record only when the database rejects it with
$deleteFallbackException. Yii’s own BaseActiveRecord::delete() keeps deleting the row physically.
ScopedQuery and QueryBehavior provide query scoping.
The owner may declare public beforeSoftDelete(), afterSoftDelete(), beforeRestore() and afterRestore()
methods; the behavior calls them by name before triggering the matching event. A before-method returning a falsy
value cancels the operation.
Every write targets the row by its persisted primary key and honors BaseActiveRecord::optimisticLock(),
whose value must be a non-negative integer that still matches the row and that each update increments. A record
without its primary key loaded, a hook that is not public, or a transactional operation on an owner without a Yii
SQL connection raises InvalidConfigException.
Exceptions from hooks, event handlers and the database propagate. A rolled-back transaction first returns the owner
attributes to their state before the call; when the rollback itself fails, RuntimeException reports it with
the exception that caused the rollback as its previous one.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$allowDeleteCallback | mixed | Callback that decides whether softDelete() deletes the row physically instead of marking it, or null to always mark it. Default: null. | DeleteBehavior |
$deleteFallbackException | string | Class name of the Throwable that makes safeDelete() fall back to a soft delete when the physical delete raises it or one of its subclasses. Default: \. | DeleteBehavior |
$invokeDeleteEvents | bool | Whether softDelete() runs the owner’s BaseActiveRecord::beforeDelete() and BaseActiveRecord::afterDelete(). Default: true. | DeleteBehavior |
$owner | yii\ | The owner of this behavior Default: null. | yii\ |
$restoreAttributeValues | array<string, | Values written on restoration, by attribute name. Default: null. | DeleteBehavior |
$softDeleteAttributeValues | array<string, | Values written on soft deletion, by attribute name, such as a flag or a status: php ['isDeleted' => true] ['statusId' => Item::STATUS_DELETED] A non-scalar callable is a computed value: it receives the owner and returns the value to write. Default: ['isDeleted' => true]. | DeleteBehavior |
$useRestoreAttributeValuesAsDefaults | bool | Whether inserting a record fills its null attributes with the restore values. Default: false. | DeleteBehavior |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__get() | Returns the value of an object property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets value of an object property. | yii\ |
__unset() | Sets an object property to null. | yii\ |
afterRestore() | Runs the owner’s public afterRestore(), when declared, and triggers EVENT_AFTER_RESTORE. | DeleteBehavior |
afterSoftDelete() | Runs the owner’s public afterSoftDelete(), when declared, and triggers EVENT_AFTER_SOFT_DELETE. | DeleteBehavior |
attach() | Attaches the behavior object to the component. | yii\ |
beforeInsert() | Fills the null attributes of a record being inserted with the restore values while $useRestoreAttributeValuesAsDefaults is enabled; handles BaseActiveRecord::EVENT_BEFORE_INSERT. | DeleteBehavior |
beforeRestore() | Runs the owner’s public beforeRestore(), when declared, and triggers EVENT_BEFORE_RESTORE. | DeleteBehavior |
beforeSoftDelete() | Runs the owner’s public beforeSoftDelete(), when declared, and triggers EVENT_BEFORE_SOFT_DELETE. | DeleteBehavior |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detach() | Detaches the behavior object from the component. | yii\ |
events() | Registers the owner event that can apply active marker defaults before insertion. | DeleteBehavior |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined. | yii\ |
init() | Initializes the object. | yii\ |
resolveRestoreAttributeValues() | Returns the values written on restoration. | DeleteBehavior |
restore() | Restores a soft-deleted record by writing the restore values together with its other changed attributes. | DeleteBehavior |
safeDelete() | Deletes the row physically and marks the record as deleted instead when the database rejects the delete with $deleteFallbackException. | DeleteBehavior |
softDelete() | Marks the record as deleted by writing $softDeleteAttributeValues together with its other changed attributes, or deletes it physically when $allowDeleteCallback allows it. | DeleteBehavior |
isDeleteAllowed() protected | Returns whether softDelete() deletes the row physically, as decided by $allowDeleteCallback. | DeleteBehavior |
restoreInternal() protected | Writes the restore values together with the other changed owner attributes. | DeleteBehavior |
softDeleteInternal() protected | Runs the soft-delete hooks around writing $softDeleteAttributeValues with the other changed attributes. | DeleteBehavior |
Events
Section titled “Events”| Event | Type | Description | Defined by |
|---|---|---|---|
EVENT_AFTER_RESTORE | yii\ | Triggered after a record is restored. Event name: 'afterRestore'. | DeleteBehavior |
EVENT_AFTER_SOFT_DELETE | yii\ | Triggered after a record is marked as deleted. Event name: 'afterSoftDelete'. | DeleteBehavior |
EVENT_BEFORE_RESTORE | yii\ | Triggered before a record is restored; set ModelEvent::$isValid to false to cancel. Event name: 'beforeRestore'. | DeleteBehavior |
EVENT_BEFORE_SOFT_DELETE | yii\ | Triggered before a record is marked as deleted; set ModelEvent::$isValid to false to cancel. Event name: 'beforeSoftDelete'. | DeleteBehavior |
Property details
Section titled “Property details”$allowDeleteCallback
Section titled “$allowDeleteCallback ”public mixed $allowDeleteCallback = nullCallback that decides whether softDelete() deletes the row physically instead of marking it, or null to always mark it.
The callback receives the owner and must return a bool; any other callback
result, or a value that is not callable, makes softDelete() throw InvalidConfigException.
static fn (\yii\db\BaseActiveRecord $user): bool => $user->lastLoginDate === null$deleteFallbackException
Section titled “$deleteFallbackException ”public string $deleteFallbackException = \yii\db\IntegrityException::classClass name of the Throwable that makes safeDelete() fall back to a soft delete when the physical delete raises it or one of its subclasses.
The default handles database integrity failures such
as a restrictive foreign key. A value that does not name a Throwable type makes safeDelete()
throw InvalidConfigException.
$invokeDeleteEvents
Section titled “$invokeDeleteEvents ”public bool $invokeDeleteEvents = trueWhether softDelete() runs the owner’s BaseActiveRecord::beforeDelete() and BaseActiveRecord::afterDelete().
The soft-delete hooks and events run in either case.
$restoreAttributeValues
Section titled “$restoreAttributeValues ”public array<string, mixed>|null $restoreAttributeValues = nullValues written on restoration, by attribute name.
When null,
resolveRestoreAttributeValues() infers them from $softDeleteAttributeValues.
$softDeleteAttributeValues
Section titled “$softDeleteAttributeValues ”public array<string, mixed> $softDeleteAttributeValues = ['isDeleted' => true]Values written on soft deletion, by attribute name, such as a flag or a status: php ['isDeleted' => true] ['statusId' => Item::STATUS_DELETED] A non-scalar callable is a computed value: it receives the owner and returns the value to write.
A string is always a literal value, even when it names a function.
['deletedAt' => static fn (\yii\db\BaseActiveRecord $model): int => time()]Method details
Section titled “Method details”afterRestore()
Section titled “afterRestore() ”public function afterRestore(): voidRuns the owner’s public afterRestore(), when declared, and triggers EVENT_AFTER_RESTORE.
Throws
yii\base\InvalidConfigException: When the owner declaresafterRestore()with a visibility other than public.
afterSoftDelete()
Section titled “afterSoftDelete() ”public function afterSoftDelete(): voidRuns the owner’s public afterSoftDelete(), when declared, and triggers EVENT_AFTER_SOFT_DELETE.
Throws
yii\base\InvalidConfigException: When the owner declaresafterSoftDelete()with a visibility other than public.
beforeInsert()
Section titled “beforeInsert() ”public function beforeInsert(yii\base\Event $event): voidFills the null attributes of a record being inserted with the restore values while
$useRestoreAttributeValuesAsDefaults is enabled; handles BaseActiveRecord::EVENT_BEFORE_INSERT.
Parameters
| Parameter | Type | Description |
|---|---|---|
$event | yii\ |
Throws
yii\base\InvalidConfigException: When the restore values cannot be inferred.
beforeRestore()
Section titled “beforeRestore() ”public function beforeRestore(): boolRuns the owner’s public beforeRestore(), when declared, and triggers EVENT_BEFORE_RESTORE.
Returns
bool: Whether the restoration may proceed; false when the owner method returns a falsy value, in which case the event is not triggered, or when an event handler invalidates the event.
Throws
yii\base\InvalidConfigException: When the owner declaresbeforeRestore()with a visibility other than public.
beforeSoftDelete()
Section titled “beforeSoftDelete() ”public function beforeSoftDelete(): boolRuns the owner’s public beforeSoftDelete(), when declared, and triggers EVENT_BEFORE_SOFT_DELETE.
Returns
bool: Whether the soft deletion may proceed; false when the owner method returns a falsy value, in which case the event is not triggered, or when an event handler invalidates the event.
Throws
yii\base\InvalidConfigException: When the owner declaresbeforeSoftDelete()with a visibility other than public.
events()
Section titled “events() ”public function events(): array<string, string>Registers the owner event that can apply active marker defaults before insertion.
Returns
array<string, string>: Owner events handled by the behavior.
resolveRestoreAttributeValues()
Section titled “resolveRestoreAttributeValues() ”public function resolveRestoreAttributeValues(): array<string, mixed>Returns the values written on restoration.
Returns $restoreAttributeValues when set. Otherwise infers each value from
$softDeleteAttributeValues: a bool is negated, 0 and 1 swap, and a computed value restores to null.
Returns
array<string, mixed>: Values by attribute name.
Throws
yii\base\InvalidConfigException: When a soft-delete value has no inferable counterpart.
restore()
Section titled “restore() ”public function restore(): false|intRestores a soft-deleted record by writing the restore values together with its other changed attributes.
Runs inside a transaction when the owner declares ActiveRecord::OP_UPDATE transactional.
Returns
false|int: Number of restored rows; 0 for an unsaved record, when no value differs from the loaded ones, or when no row matched; false when a hook or event handler cancels the restoration.
Throws
yii\base\InvalidConfigException: When the restore values cannot be inferred or an owner requirement is not met.yii\db\StaleObjectException: When the optimistic lock value is invalid, cannot be incremented, or is outdated.RuntimeException: When a rollback fails after an exception.
safeDelete()
Section titled “safeDelete() ”public function safeDelete(): false|intDeletes the row physically and marks the record as deleted instead when the database rejects the delete with
$deleteFallbackException.
Requires a SQL ActiveRecord owner. The physical attempt runs BaseActiveRecord::beforeDelete() and
BaseActiveRecord::afterDelete() inside a transaction. When the physical delete raises an eligible
exception, that transaction is rolled back and the soft deletion runs in a new one. An exception raised by a
hook is never eligible.
Returns
false|int: Number of deleted or marked rows; 0 for an unsaved record or when no row matched; false when a hook or event handler cancels the operation.
Throws
yii\base\InvalidConfigException: When the owner or$deleteFallbackExceptionis invalid.yii\db\StaleObjectException: When the optimistic lock value is invalid, cannot be incremented, or is outdated.RuntimeException: When a rollback fails after an exception.
softDelete()
Section titled “softDelete() ”public function softDelete(): false|intMarks the record as deleted by writing $softDeleteAttributeValues together with its other changed
attributes, or deletes it physically when $allowDeleteCallback allows it.
Marking the record runs inside a transaction when the owner declares ActiveRecord::OP_DELETE or
ActiveRecord::OP_UPDATE transactional. The physical delete is BaseActiveRecord::delete(), which
follows ActiveRecord::OP_DELETE alone.
Returns
false|int: Number of affected rows; 0 for an unsaved record, when no value differs from the loaded ones, or when no row matched; false when a hook or event handler cancels the operation.
Throws
yii\base\InvalidConfigException: When$allowDeleteCallbackis invalid or an owner requirement is not met.yii\db\StaleObjectException: When the optimistic lock value is invalid, cannot be incremented, or is outdated.RuntimeException: When a rollback fails after an exception.
isDeleteAllowed()
Section titled “isDeleteAllowed() ”protected function isDeleteAllowed(): boolReturns whether softDelete() deletes the row physically, as decided by $allowDeleteCallback.
Returns
bool: Whether the physical delete is allowed; false when no callback is configured.
Throws
yii\base\InvalidConfigException: When the callback is not callable or does not return abool.
restoreInternal()
Section titled “restoreInternal() ”protected function restoreInternal(): intWrites the restore values together with the other changed owner attributes.
Returns
int: Number of restored rows.
Throws
yii\base\InvalidConfigException: When the restore values cannot be inferred or the primary key is not loaded.yii\db\StaleObjectException: When the optimistic lock value is invalid, cannot be incremented, or is outdated.
softDeleteInternal()
Section titled “softDeleteInternal() ”protected function softDeleteInternal(): false|intRuns the soft-delete hooks around writing $softDeleteAttributeValues with the other changed attributes.
Returns
false|int: Number of rows marked as deleted, or false when a hook or event handler cancels.
Throws
yii\base\InvalidConfigException: When the primary key is not loaded or an owner hook is not public.yii\db\StaleObjectException: When the optimistic lock value is invalid, cannot be incremented, or is outdated.