ProcessWire icon indicating copy to clipboard operation
ProcessWire copied to clipboard

Behaviour of $users->add

Open CaelanStewart opened this issue 8 years ago • 3 comments

Hi,

This is on the latest version of ProcessWire (3.0.17).

Basically, when I call $u = $users->add('some-name'), the User object is returned as per usual, but it also saves the user to the database WITHOUT me even having to call $u->save().

This caused some confusion earlier, because if a user with the same name already exists, a NullPage is returned instead of a fresh user object. I had not realised the user had already been saved automatically, so I was then thinking that the ->add method was misbehaving and returning the wrong thing. After a little while, I try changing the username being passed to >add, and suddenly the object returned by it was a User object. I reload the page, and it's a NullUser again.

I remember seeing somewhere that it was one of ProcessWire's design concepts that information is not saved without the user triggering it? My memory may be incorrect, but from what I can remember, the current behaviour does not align with that concept.

Thanks in advance.

CaelanStewart avatar May 11 '16 13:05 CaelanStewart

Pages::add as well as PagesType::add do both add a page and save it, which isn't new behavior for both.

LostKobrakai avatar May 11 '16 14:05 LostKobrakai

OK, I see.

Just thought I'd point it out in case it was a mistake.

It might be worth noting that in the documentation so other people don't have the same problem, since creating a new user via...

$u = new User();
$u->name = 'some-name';
$u->save();

...does not save it before the 3rd line is executed.

The code example on the PW docs, when looked at with no PW experience would imply the user is only saved once the 4th line has been executed:

<?php
$u = $users->add('gonzo');
$u->pass = "BamBam!";
$u->addRole("superuser");
$u->save();

CaelanStewart avatar May 11 '16 14:05 CaelanStewart

This is actually the purpose of the add() method, just to save you a step or two relative to doing a new User(). All Pages/PagesType operations are database operations, and those API vars exist exclusively to interact with the database. For cases where you don't want that behavior, it's perfectly fine to use the regular way like in your first example above.

ryancramerdesign avatar Jun 03 '16 17:06 ryancramerdesign