3

I have a channel in which each channel entry has a "users" field type that is limited to one user. My code below works fine when the user is not suspended, however if I suspend the user, the then $entry->user field is null rather than set to the array of one user like its normally set to.

Here is my code:

        // do criteria code to get pending transfers from patients channel
    $account = $userIdentity->getFieldValue('account')->first();
    $entryQuery = Entry::find()
        ->section('networkAssets')
        ->relatedTo(['targetElement' => $account, "field" => "account"])
        ->orderBy('title asc');


    // Execute the query and get the results
    $entries = $entryQuery->anyStatus()->all();
    $assets = [];
    foreach($entries as $entry) {
        $user = $entry->user->one();
        $assets[] = [
            'id' => $entry->id,
            'slug' => $entry->slug,
            'title' => $entry->title,
            'email' => $user->email,
            'first_name' => $user->firstName,
            'last_name' => $user->lastName,
            'address1' => $entry->address1,
            'address2' => $entry->address2,
            'state_province' => $entry->stateProvince,
            'city' => $entry->city,
            'postal_code' => $entry->postalCode,
            'country' => $entry->country,
            'username' => $user->username,
            'password' => '',
            'status' => $user->getStatus(),
            'date_created' => $entry->dateCreated->format('m/d/Y') . "<br>" . $entry->dateCreated->format('H:i:s T'),
            'last_login' => $user->lastLoginDate ? $user->lastLoginDate->format('m/d/Y') . "<br>" . $user->lastLoginDate->format('H:i:s T') : 'Never',
            'phone' => $entry->phoneNumber
        ];
    }

    return $assets;

You can see in the foreach loop that Im getting the user from the looped entry result and storing it in a $user variable.

When I try to use $user I get a notice because $user is null.

How can I force this code to return the linked user in the user field even when the user is suspended?

| improve this question | | | | |
  • The ->anyStatus()-> was me just trying things to get this to work... – SublymeRick Aug 6 '19 at 17:22
3

User queries by default will only return active users, not pending or suspended ones.

To include suspended users, change this line:

$user = $entry->user->one();

to this:

$user = $entry->user->status(['active', 'suspended'])->one();

Or if you want to include pending users as well (users who haven’t activated their account yet), you can do this:

$user = $entry->user->anyStatus()->one();
| improve this answer | | | | |
  • This did the trick! thanks! (spelling is hard) – SublymeRick Aug 6 '19 at 17:31

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.