migxLoopCollection filter results by single-select dropdown in frontend (also how to setup a man2many custom table)

Now that you created a second database table you will have to change your MIGX-configuration to still be able to manage your trainers in the backend.

Add this code in the tab MIGXdb-Settings in the field Hook Snippets:

{"aftergetfields":"trainerteam_aftergetfields","aftersave":"trainerteam_aftersave"}

Then create 2 new snippets trainerteam_aftergetfields and trainerteam_aftersave.

trainerteam_aftergetfields

<?php
$base_path = $modx->getOption('core_path').'components/trainerteam/';
$modx->addPackage('trainerteam', $base_path.'model/');

if ($object) {
    $record_fields = $object->get('record_fields');
    $trainer_id = $record_fields['object_id'];
    
    $team_ids = array();
    $result = $modx->getCollection('TrainerMannschaften', array('trainer_id' => $trainer_id));
    foreach($result as $res){
        $team_ids[] = $res->get('mannschaft_id');
    }
    
    $record_fields['mannschaften'] = implode("||",$team_ids);
    $object->set('record_fields',$record_fields);
}

return '';

This snippets reads all the team-ids for a specific trainer from the table trainer_mannschaften, combines them into a string (delimited with ||) and stores them in a field called mannschaften so that it can be used with a listbox-multiple dropdown.

trainerteam_aftersave

<?php
$base_path = $modx->getOption('core_path').'components/trainerteam/';
$modx->addPackage('trainerteam', $base_path.'model/');

$object = & $modx->getOption('object',$scriptProperties,null);
$trainer_id = $object->get('id');

//query everything that is already saved in the database
$teams_old = array();
$result= $modx->getCollection('TrainerMannschaften', array('trainer_id' => $trainer_id));
foreach($result as $res){
    $teams_old[] = $res->get('mannschaft_id');
}

$str_teams = $object->get('mannschaften');
$teams_new = explode('||',$str_teams);
foreach($teams_new as $team_id){
    if ($team_id === ''){
        //no teams selected for this trainer
        break;
    }
    
    $team_id = (int)$team_id;
    $pos = array_search($team_id, $teams_old);
    if (false !== $pos){
        //team-id is already saved in the database
        unset($teams_old[$pos]);
    } else {
        //add new team-id
        $new_t = $modx->newObject('TrainerMannschaften');
        $new_t->set('mannschaft_id',$team_id);
        $new_t->set('trainer_id',$trainer_id);
        $new_t->save();
    }
}

//delete remaining team-ids from the database
foreach($teams_old as $team_id){
    $entry = $modx->getObject('TrainerMannschaften',array('trainer_id' => $trainer_id, 'mannschaft_id' => $team_id));
	$entry->remove();
}

This snippets breaks the string (delimited with ||) with all the team-ids into the individual ids and makes sure, they match the data in the table trainer_mannschaften.

2 Likes