New modifeid snippet (tested):
<?php
/*
* Snippet add button on page to save current document to extended user field or remove it.
* Requirements: Login Extra, created extended field for each user: Favorite Page, Change redirect page for not logged user, set max value
*
* Call on page:
* [[!saveFavorite]]
* <form action="[[~[[*id]]]]" method="post">
* <input type="hidden" name="favorite_page" value="[[*id]]" />
* <input type="submit" name="fav_submit" [[+FavPH]] />
* </form>
*/
$max = 14; //maximum allowed favorites
$modx->setPlaceholder('FavPH','class="fav-star" title="Please log in" value="Login to add to favorites" '); //initialize default button value
$id = $modx->resource->get('id'); //current id
$sent_id = (int) $_POST['favorite_page']; //posted id of saved page
if ($modx->user->hasSessionContext($modx->context->get('key'))) { // if logged in
// Get the user's extended fields
$profile = $modx->user->getOne('Profile');
$fields = $profile->get('extended');
$fav_field = explode(",", $fields['Favorite Page']); // change string to array
if ((count($fav_field) > $max) and ($sent_id == $id)) { //if more then max value
$modx->setPlaceholder('FavPH','class="fav-star" title="Add to Favorites" value="Add to Favorites" '); // change placeholder text
return "Max amount of " . $max . " pages in favorites reached!"; // do not add new value, return warning
}
if (in_array($id, $fav_field)) { // if found in array
if ($sent_id == $id) { // if clicked to form button
foreach (array_keys($fav_field, $sent_id) as $key) unset($fav_field[$key]); // page is removed from favorites
$modx->setPlaceholder('FavPH','class="fav-star" title="Add to Favorites" value="Add to Favorites" '); // change placeholder text
$fields['Favorite Page'] = implode(",", $fav_field); //put the rest back in extended field
$profile->set('extended',$fields);
$profile->save();
return;
} // change placeholder text if already in field but button not clicked
$modx->setPlaceholder('FavPH',' class="fav-star-selected" title="Remove from Favorites" value="Remove from Favorites" ');
return;
}
if (empty($sent_id)) { //document not yet added to fav and button not clicked
$modx->setPlaceholder('FavPH',' class="fav-star" title="Add to Favorites" value="Add to Favorites"');
return;
}
else array_push($fav_field, $sent_id); //document not yet added to fav but button IS clicked, add new id to extended field
$fields['Favorite Page'] = implode(",", $fav_field); //convert array to string
$profile->set('extended',$fields);
$profile->save();
$modx->setPlaceholder('FavPH',' class="fav-star-selected" title="Remove from Favorites" value="Remove from Favorites"');//change placehodler
return;
}
if ($sent_id == $id) { //if not logged in redirect to login page (57) - change it!
$url = $modx->makeUrl(57);
$modx->sendRedirect($url);
}
return;
For listing favorite pages, use Login snippet and GetResources:
[[!Profile]]
[[!getResources? &parents=`-1` &resources=`[[+Favorite Page]]` &tpl=`myRowTpl`]]