User variable as parent

Hello,

unfortunately I need help again.

I create Children with Page::create(). So far everything works, including the assignment to a parent page. A parent page is a page that always has the same title as the user’s ID.

However, if I now want to replace the parent information with a variable, the child page is no longer assigned to the parent, but is created as a page of the first level.

What’s the reason?

Here is my code:

$userID = $kirby->user()->id();

        $newPage = Page::create([
          'slug' => $data['name'],
          'draft' => false,
          'template' => 'file',
          'parent' => page($userID),
          'content' => [
            'title' => $data['name']
          ]
        ]);

I have already tried $pages->find($userID) instead of page($userID), but unfortunately that doesn’t work either.

Thank you very much!

Could you show us what your page structure looks like?

Thanks for the quick reply.

As top level pages I have two pages, named as the IDs of my two users.

The pages I want to create with Page:create() should be children of the top level page assigned to ID of the current logged in user.

Ok, thanks. In which context are you using the above code snippet? Theoretically it should work fine. If you hard-code the page id, it works?

Inside a function in the page controller. The kirby, page and pages objects are assigned to the controller.

When I replace the variable by a sample user ID, everything is working fine.

But do you define $kirby inside that function or pass it as paramater?

I pass it as parameter.

return function ($kirby, $page, $pages, $site) {
...
}

Although, when I add

$kirby = kirby();

nothing changes.

It would be helpful if you post the relevant method inside your controller, if it is not too long, post the complete controller, otherwise remove everything that is not important.

I solved the problem, even if I don’t know exactly why.

$userID = $kirby->user()->id(); was previously within the If condition if ($kirby->request()->is('POST') && get('createFile')).

Now I have defined $userID before the if condition and it works.

Thank you anyway for the help!