Search code examples
databasepowerapps

MS Power Apps producing unwanted duplicate records


world! I've started a new position recently and have been struggling to find out why the code below is creating duplicate records within the popMode = "Move" section. It's written in MS Power Apps and the code is to assign students to a particular group. When added initially students group is set to 0. I can then move the student to another group 1 or 2. Student is deleted from group 0 and a new record is created in either group 1 or 2. The problem is when I try to move students from group 1 to 2 for example the code seems to be creating a new record in group 1 and 2 resulting in unwanted duplicate records. I'd like to either remove the original record or update it to the new group.

If(
    popMode = "Add",
    RemoveIf(
        tt_tgroup_membership,
        student_id = popListStu_1.Text && tgroup_id = popListGroup_1.Selected.tgroup_id
    );
    Patch(
        tt_tgroup_membership,
        Defaults(tt_tgroup_membership),
        {
            student_id: popListStu_1.Text,
            tgroup_id: popListGroup_1.Selected.tgroup_id
        }
    ),
    popMode = "Copy",
    ForAll(
        check_stu,
        Patch(
            tt_tgroup_membership,
            Defaults(tt_tgroup_membership),
            {
                student_id: ThisRecord.student_id,
                tgroup_id: popListGroup_1.Selected.tgroup_id
            }
        )
    ),
    popMode = "Move",
    ForAll(
        check_stu,
        Patch(
            tt_tgroup_membership,
            If(
                ThisRecord.tgroup_id = 0,
                Defaults(tt_tgroup_membership),
                LookUp(
                    tt_tgroup_membership,
                    student_id = ThisRecord.student_id && tgroup_id = ThisRecord.tgroup_id
                )
            ),
            {
                student_id: ThisRecord.student_id,
                tgroup_id: popListGroup_1.Selected.tgroup_id 
            }
        )
    )
);

Refresh(v_tt_student_enrols);
ClearCollect(
    student_groups,
    Filter(
        v_tt_student_enrols,
        cost_id = current_cost.cost_id
    )
); Clear(check_stu);
UpdateContext({popVis: false});

I've tried adding: RemoveIf( tt_tgroup_membership, student_id = ThisRecord.student_id && tgroup_id = ThisRecord.tgroup_id );

and: Remove( Filter( tt_tgroup_membership, student_id = ThisRecord.student_id && tgroup_id = ThisRecord.tgroup_id ), after check_stu,

but neither of these had the desired effect.

Thanks in advance for any help!


Solution

  • I am assuming that there's a collection called student_groups and it has a column which specifies the group, 0, 1 or 2.

    I'd create a gallery with the source student_groups and add a dropdown in the template. On the dropdown with items [0,1,2], I can put a patch function on the onchange trigger to change the group value, like, Patch(student_groups,ThisItem,{GroupColumn:Self.Selected.Value})