Clone if not empty

Hi all, I'm in the situation where I have two objects of the same entity, which I want to 'merge' or 'intersect', where one of the objects has preference over the other. Let's call them object 1 and object 2.  Object 1 has members a, b and c filled, Object 2 has members a,  c and d filled. I'm looking for a functionality to overwrite/fill the members of Object 1 with the members of Object 2, only if the members of Object 2 are not empty. Then I would end up with Object 1 with members a (copied from Object 2), b, c (copied from Object 2) and d (copied from Object 2) Meaning, for every member of Object 1, a similar check must be made: Object1/MemberA: if $Object2/MemberA != empty then $Object2/MemberA else $Object1/MemberA However, this is not convenient to write for all members of the object, even more so since the object also has associated objects that need the same functionality. Also, it is not easy to maintain on the long term.   I was hoping a community commons java action catered for this function, something like 'clone if not empty', but that was not the case. Even shorter would be to only check the non empty members of Object 2 and fill the corresponding Object 1 members with these values.   Does anyone have experience with a similar issue?  
2 answers

Hi Thijs,

To the best of my knowledge there is no such function in the community commons. But it should be fairly straightforward to write it yourself.

In java you can get all the attributes and associations (in java "members") of an object and iterate over them in a loop. Maybe something in the lines of

for ( String member_name : object1.getMembers(context).keySet )
    if ( object2.getValue(context, member_name)!= null )
        object1.setValue(context, member_name, object2.getValue(context, member_name));

You can also look at how the community commons module does it here -

Hope this helps,



Thanks Andrej,

I indeed re-used the code from the Community Commons 'CloneObject' action, so that you can also exclude associations if you'd like.

IContext context = this.getContext();
	// Should be improved by only iterating over the members that you want to clone
	// (not an instance of MendixObjectReference/MendixObjectReferenceSet, not an autonumber, m.GetValue != null and m.getValue != "" )
	Map<String, ? extends IMendixObjectMember<?>> members = Source.getMembers(context);	
	for(String key : members.keySet()) { 
		IMendixObjectMember<?> m = members.get(key);
		if (m.isVirtual())
		if (m instanceof MendixAutoNumber)
		if (WithAssociations || ((!(m instanceof MendixObjectReference) && !(m instanceof MendixObjectReferenceSet)&& !(m instanceof MendixAutoNumber))))
			if (m.getValue(context) != null && m.getValue(context) != "")
			Target.setValue(context, key, m.getValue(context));