how to use setFormatter for supporting a password field that isn't changing
how to use setFormatter for supporting a password field that isn't changing

I have a password field that is stored has a hash in sql. On my datatable editor form, I have two client side fields used for setting a new password. In presubmit, I check the values of the client side password and if they both match, then I set the field in the datatable to the new password.
The issue I am having is in the server side php. I want to ignore the field if it's empty, if it's not empty then set the hash, I am getting an Undefined constant "NO_FORMATTER_APPLIED"
Field::inst( 'UserPassword' )
->getFormatter( function () {
return ''; // Return empty string on read
} )
->set( Field::SET_BOTH ) // Allow setting on create and edit
->get( false ) // Do not send password hash to client
->setFormatter( function ( $val, $data, $field ) {
if ( ! empty( $val ) ) { // Check if a new password was provided
return password_hash( $val, PASSWORD_DEFAULT ); // Hash and return new password
}
return Field::NO_FORMATTER_APPLIED; // Keep existing password if not provided
} ) ,
This question has accepted answers - jump to:
Answers
Hi,
Don't use
setFormatter
for this - that's for transforming a field's value - i.e. it is always written. Instead, usepreCreate
andpreEdit
server-side events Check if a new value was submitted, and if it was use->setValue()
to set the hashed value as the one to write.It was a while ago, but I wrote some example code in a 2015 blog post.
Allan
In addition to Allan's comment maybe my solution for this could be helpful.
I also check whether a user has ever been active. And that is the case if there is a saved password in the database.
The custom setFormatter handles that for me.
Sorry, I forgot to address Allan's valid point!
How am I achieving that the password is only written if
- both passwords are not empty (i.e. the user really wants to change the password)
- both passwords are identical and valid?
That is done with the validators!
Even if the first validator returns true, the second validator for the repeat password will return an error message, if the first password was empty and the repeat password was filled. That means that the setFormatter will be irrelevant if the validators return errors.
Here is part of the code that achieves that:
Oh, it is too long ago. Sorry!
I also need the event handlers Allan was talking about to make sure no updates happen if the password-field isn't filled on the client side. That's in addition to my code above.