Creating a password hash to send to the database with Editor

Creating a password hash to send to the database with Editor

StreakDragonStreakDragon Posts: 2Questions: 1Answers: 0

I'm completely new to DataTables and DataTables Editor, but so far everything has worked great. I've run into this one issue though I need to hash out a password using password_hash() and send it to the database, if a new password has been entered. I thought this would be pretty simple and followed some examples I saw online. However I get a "System Error" message when submitting it with no further information on the issue.

Here is my code:

Field::inst('password')
     ->setFormatter( function($val) {
    
     $newPassword = trim($val);
    
      if($newPassword === '') {
          return Editor::dbNull();
     }
     else {
         return password_hash($newPassword, PASSWORD_DEFAULT);
     }
     })

What seems to be the issue with this? Thanks in advance for any and all help!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,966Questions: 1Answers: 10,547 Site admin
    Answer ✓

    A system error message means that the server is returning invalid JSON. That normally has an error message that will indicate what the problem is.

    I'd actually suggest using the preEdit and preCreate events for this, as you probably want slightly different behaviour for the field for create and edit. e.g. on create, add a validator to make sure it is set, but on edit, it could be blank in which case you don't want to set it:

    ->on('preEdit', function ($editor, $id, $values) {
      if (! $values['password']) {
        $editor->field('password')->set(false);
      }
      else {
        $editor->field('password')->setValue(
          password_hash($values['password'], PASSWORD_DEFAULT) 
        );
      }
    })
    

    Allan

  • StreakDragonStreakDragon Posts: 2Questions: 1Answers: 0

    Ah! Thank you so much, that worked brilliantly! And you're right, I will definitely want to do something with preCreate so this also answers that unasked question! Thanks so much @allan

Sign In or Register to comment.