Empty Password Field, disable writing to database

Empty Password Field, disable writing to database

th3t1ckth3t1ck Posts: 147Questions: 27Answers: 1
edited February 6 in Editor

I have a password field that when a new user is created I want to write the password to the database. That works fine and encrypts the password using the following.

$out=Editor::inst( $db, 'users' )
    ->field(
        Field::inst( 'password' )
            ->get( false ) // never read from the db
                ->setFormatter ( function ( $val, $data ) {
                    return crypt( $val, '$somerandomsalthere$' );
                }),
...

However if you edit an existing users information and do not specify a password a null is encrypted and the user's password is changed. I don't want to encrypt a blank/null password only a change such as a password reset.

I have been trying to figure this out and only have gotten this far unsuccessfully...

$out=Editor::inst( $db, 'users' )
    ->field(
        Field::inst( 'password' )
            ->get( false ) // never read from the db
                ->validator( function ( $editor, $action, $data, $val ) {
                    if ( $action === Editor::ACTION_CREATE ) {
                        ->setFormatter ( function ( $val, $data ) {
                            return crypt( $val, '$somerandomsalthere$' );
                        })
                    } else if ( $action === Editor::ACTION_EDIT ) {
                        Field( 'users' ).set(false);
                        return;
                    }
                } ),
...

It doesn't like the ->setFormatter. Evidently it doesn't belong there. How else can I accomplish this?

Answers

  • th3t1ckth3t1ck Posts: 147Questions: 27Answers: 1

    Tried this also but just not sure how to read the value of the field and check it for null and then disable the setting of the value in the database for this password field.

    ->setFormatter ( function ( $editor, $action, $val ) {
                        if( $action === Editor::ACTION_CREATE ) {
                            return crypt( $val, '$somerandomsalthere$' );
                        } elseif( ( $action === Editor::ACTION_EDIT ) && ( Field('.password').val() !==null ) ) {
                            return crypt( $val, '$somerandomsalthere$' );
                        } else {
                            Field('.password').set(false);
                            return;
                        }
                    }),
    ...
    
  • allanallan Posts: 51,453Questions: 1Answers: 7,759 Site admin
    edited February 6
  • th3t1ckth3t1ck Posts: 147Questions: 27Answers: 1

    Thank you Allen. I didn't think of using preEdit although I am using preCreate to check password length and if the password and confirm password matches. I'll give it a shot and get back to you.

Sign In or Register to comment.