2

I have some categories, and with the use of a category field a user can select these from within his / her profile.

Which is shown in the image:

enter image description here

In my Twig template I can get the user selections out using the following code.

{% set property_prefs = craft.categories({
    relatedTo: { sourceElement: currentUser, field: "propertyPreference" },
    limit:     null
}) %}

But what I want to know is how can I programmatically save a user selection using the API from within my plugin.

Also, which table are these stored in?

1

I had to do something similar to this in a plugin recently, Inserting Relationship Into Entries Field - Plugin Not Saving Relation, I know it's users to an entry field but I would assume the methods are similar.

So you will need 3 things in order to save a users categories

1. The Craft\FieldModel of the field which has the associations

$field = craft()->fields->getFieldByHandle('propertyPreference');

2. The source, in this case the matrix block that has the field

$source = craft()->matrix->getBlockById(<someId>);

3. An array of element id's you wish to relate to the field

$relations = $user->propertyPreference->ids();

Once you have those you can edit the $relations array however you see fit and then simply save the relations back

craft()->relations->saveRelations($field , $source, $relations);

You can find out more about the save relations function in the class reference

As for which table, I would assume they are in craft_relations

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.