0

I have a Category "Colors". This category has: Blue, Red, Green

I've added a custom users field (CP > Settings > Users > Fields), this field is the category type. "Colors". In the front of website I need users to select their faviourte color/s and save/update it.

Below code saves successfully "Settings saved!", but I go into the CP > Users > user@gmail.com > (custom field category colors) and the colors have not been selected:

enter image description here

    public function actionUpdateSettings()
    {
        $this->requirePostRequest();

        $request            = Craft::$app->getRequest();
        $myUser             = Craft::$app->getUser()->getIdentity();
        $cat                = $myUser->getAttributes()['colors']->all(); // Get users seletected colors
        $availableColors    = Category::find()->group('colors')->all(); // Query all available colors

        // Organise array for users already seletected color items
        $usersCurrentColors = array();
        foreach($cat as $item)
        {
            array_push($usersCurrentColors, $item['slug']);
        }

        // Organise all available colors to tailor to format
        $organiseAvailableColors = array();
        foreach($availableColors as $item)
        {
            $organiseAvailableColors[] = $item['slug'];
        }

        $allAvailableColors       = array_fill_keys($organiseAvailableColors, '');

        // Organise new selected colors from the form(post data)
        $newSelectedColors  = array_intersect_key($request->getBodyParams(),$allAvailableColors);

        // Set the new data that soon will be saved
        $myUser->setAttributes(array(
            'colors' =>  Category::find()->group('colors')->slug($newSelectedColors),

        ), false);

        // Save data and create error messages
        $save = Craft::$app->getElements()->saveElement($myUser);

        if($save){

            return Craft::$app->session->setFlash('success_userSettings', 'Settings saved!');

        }else{
            return Craft::$app->session->setFlash('success_userSettings', 'Settings failed, please contact support!');
        }

    }

Craft Pro: 3.4.6.1

  • What type field are you using on the front end form and can users select multiple categories? – Oli Feb 26 at 12:33
  • @Olii Checkbox on front end. – Jessica Talzor Mar 1 at 21:51

Your Answer

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

Browse other questions tagged or ask your own question.