Cybo Advanced Field EngineCyboweb Technologies · Documentation · v1.0.2

cafe_save_values()

Purpose

Saves several field values of one object at once. Every value is checked first; when any value is invalid nothing is saved. The values are then written in one database transaction, so an object never ends up half updated.

Use it in imports, form handlers and migration code instead of calling cafe_update_field() once per field.

Syntax

cafe_save_values( array $values, mixed $object_id = null, ?string $object_type = null ): bool

Parameters

Parameter Type Default Description
$values array - Values keyed by field name (or field key). The value shapes are the same as for cafe_update_field(): IDs for images, galleries and references, a list of rows for a Collection, _section in each Section Builder row, sub-field values for a Field Set.
$object_id mixed null Which object. null means the current object. See the $object_id argument.
$object_type string|null null Object type, or null to infer it.

Return value

true when every value was saved. false when a field does not exist, the object does not exist, or any value is invalid (then nothing was saved).

Example

$saved = cafe_save_values(
	[
		'price'        => 450000,
		'hero_image'   => 91,                   // attachment ID
		'features'     => [ 'garden', 'garage' ],
		'team_members' => [                     // Collection: one array per item
			[ 'name' => 'Anna', 'role' => 'Agent', 'photo' => 92 ],
			[ 'name' => 'Ben',  'role' => 'Photographer' ],
		],
	],
	$post_id
);

Need to know what was wrong? Use the service, which returns every problem at once:

$result = cafe()->fields()->save_values( $values, $post_id );

if ( is_wp_error( $result ) ) {
	foreach ( $result->get_error_data()['errors'] ?? [] as $problem ) {
		// $problem = [ 'field' => 'price', 'path' => 'price', 'code' => 'cafe_invalid_number', 'message' => '…' ]
		error_log( $problem['path'] . ': ' . $problem['message'] );
	}
}

Notes

  • No permission check. Like update_post_meta(), this is a developer function. Check current_user_can() yourself before saving user input.
  • Required settings are not enforced (pass true as the fourth argument of cafe()->fields()->save_values() to enforce them).
  • Fields set to Copy on a WPML translation are written to the original, exactly as with cafe_update_field().
  • Fires cafe_before_save_field and cafe_after_save_field once per field.
  • Since 0.13.0.