Create relationship to existing object using prepare_save_data

When creating a custom code studio widget, is it possible to create / change a relationship using the prepare_save_data function?

I have tried the following:

prepare_save_data: function(payload) {
	name = widget.get_setting('name');
	flag_relationship = widget.get_setting('flag_relationship ');
	let save_data = {
		[name]: payload.name,
		[flag_relationship]: payload.flag_relationship 
	};
	return save_data;
}

Where flag_relationship is a setting as below:

flag_relationship : {
	main_label:'Flag',
	base_format:'field_path',
	path_only:true
}

Which produces a value of save_data as follows:

Array
(
    [:PRO0000514GBBYC1] => 235106595
    [REL0000287GBBYC1] => 1743
)

Where 1743 is the id of the object that I wish to create a relationship to.

I’ve also tried doing this with a “:” in front of the relationship path, but in either case, although the prepare_save_data method can be seen to have run, nothing is saved.

If I comment the flag_relatioship line out of prepare_save_data the name field saves as expected.

Any suggestions? I’m hoping that I’m not trying to do the impossible here.

Try adding ‘:id’ to the relationship ID, e.g.

[REL0000287GBBYC1:id] => 1743

Assuming it isn’t being functionally blocked for any security or other reason, then that is the correct format for setting a relationship (down a to-one path at least).

1 Like

Amazing, this has worked perfectly. Thanks Bob :+1:

No problem. It may seem a little confusing as the id Attribute of a record isn’t actually writable. But when used like this it’s a special case that creates a relationship to the ID, rather than trying to overwrite it’s value. Effectively you’re setting the foreign key to the given value.