Created
February 2, 2022 09:27
-
-
Save MjHead/b413e132cebc529515b65fd4176b4617 to your computer and use it in GitHub Desktop.
JetEngine. Relations. Update related items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Update related item from form action/notification | |
* | |
* @param array $args [description] | |
* @return [type] [description] | |
*/ | |
function my_update_related_items( $args = array() ) { | |
$relation = ! empty( $args['relation'] ) ? $args['relation'] : false; | |
$parent_id = ! empty( $args['parent_id'] ) ? $args['parent_id'] : false; | |
$child_id = ! empty( $args['child_id'] ) ? $args['child_id'] : false; | |
$context = ! empty( $args['context'] ) ? $args['context'] : 'child'; | |
if ( ! $relation ) { | |
return new \WP_Error( 'rel_empty', __( 'Relation ID is not set. Please check your form settings', 'jet-engine' ) ); | |
} | |
if ( ! $parent_id ) { | |
return new \WP_Error( 'parent_empty', __( 'Parent Item ID is not set. Please check your form settings', 'jet-engine' ) ); | |
} | |
$relation_instance = jet_engine()->relations->get_active_relations( $relation ); | |
if ( ! $relation_instance ) { | |
return new \WP_Error( 'rel_not_found', __( 'Relation instance not found by ID. Please check your form settings', 'jet-engine' ) ); | |
} | |
if ( ! is_array( $parent_id ) ) { | |
$parent_id = array( $parent_id ); | |
} | |
if ( ! is_array( $child_id ) ) { | |
$child_id = array( $child_id ); | |
} | |
$relation_instance->set_update_context( $context ); | |
if ( 'child' === $context ) { | |
/** | |
* We updating children items from the parent object, | |
* this mean we need to delete all existing children for the parent and set up new | |
*/ | |
foreach ( $parent_id as $par_id ) { | |
// First of all completely delete all existing rows for the current parent | |
$relation_instance->delete_rows( $par_id ); | |
foreach ( $child_id as $c_id ) { | |
$relation_instance->update( $par_id, $c_id ); | |
} | |
} | |
} else { | |
/** | |
* We updating parent items from the child object, | |
* this mean we need to delete all existing parents for the processed child and set up new | |
*/ | |
foreach ( $child_id as $c_id ) { | |
// First of all completely delete all existing rows for the current child | |
$relation_instance->delete_rows( false, $c_id ); | |
foreach ( $parent_id as $par_id ) { | |
$relation_instance->update( $par_id, $c_id ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment