This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

billyZduke
billyZduke

I'm working on a custom plugin that significantly expands the functionality of the RainLab.User model. I've added a feature that allows one User to have many UserAddresses, and I'm trying to make a UserAddressBook component that will display all the addresses that belong to a single User. So, ideally, when I drag this component into one of my front-end partials, I want it to use the logged-in User by default.

I see in other plugins using page variables as default component property values that they use the Twig rendering syntax to set the default, as in {{ :slug }}. I've already got the ability to select any existing single user in my component properties, but how do I get the following to access the User that's logged into the page, or at the very least its id...?

class UserAddressBook extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'          => 'User Address Book',
            'description'   => 'Displays all addresses belonging to a User.'
        ];
    }

    public function defineProperties()
    {
        return [
            'user' => [
                 'title'             => 'User',
                 'description'       => 'The user whose addresses to index',
                 'default'           => '{{ :user }}',
                 'type'              => 'dropdown',
                 'placeholder'       => 'Select User',
            ]
        ];
    }
...
}

Using {{ :user }} doesn't seem to assign any value to the component's user property... What should I change it to?

Last updated

billyZduke
billyZduke

Seems like I'm answering my own questions a lot on this forum lately, but here we go. Pretty much right after I posted the above, it occurred to me that I could just remove the default from the property definition and check for $this->page['user'] instead:

public function onRun()
{
    $this->user = $this->loadUser();

    if (!$this->user) return false;
}

public function loadUser()
{
    $user_id = ($this->property('user')) ?: false;
    if (!$user_id):
        if ($this->page['user']):
            $user_id = $this->page['user']->id;
        endif;
    endif;
    if (!$user_id) return false;

    return User::where('id',$user_id)->with('addresses')->first();
}

And this seems to be working as hoped. Once again, hope this helps out someone else stuck in the same Exception-throwing headspace...

daftspunky
daftspunky

Thanks for sharing!

1-3 of 3

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.