Save Model Values Without Null

132 views Asked by At

Everytime i try attempt to update a row i receive an error which says "something is required". In codeigniter you can update rows without the need to set everything to null in the mysql tabel settings.

I just want to update one value not the entire row.

Is this possible?

if ($users->save() == false) {
    echo "Umh, We can't update the user right now: \n";
    foreach ($users->getMessages() as $message) {
        echo $message, "<br>";
    }
    $this->flash->error("Error in updating information.");
    $this->response->redirect('user/profile');
        } else {
            echo "Great, a new robot was saved successfully!";
            $this->flash->success("Member has been updaed successfully.");
            //$this->response->redirect('user/profile');
        }
2

There are 2 answers

0
yergo On BEST ANSWER

Your isseue happens because you have already filled table and not yet properly defined model. Phalcon is validating all fo model data BEFORE trying to save it. If you define your model with all defaults, skips etc. properly, updates will be fired on single columns as you wish.

If you have definitions, that does not allow nulls, but you need an empty or default value there anyway, you may want to use 'beforeCreate' actions in model implementations. Also if there are things with defaults to set on first insert, you may wanto to use skipAttributes method.

More information is in documentation: Working with Models. So far best bit over internet I've found.

Also, below is an example for nullable email column and NOT NULL DEFAULT '0' 'skipped' column from my working code:

public function initialize() {
    $this->skipAttributesOnCreate(['skipped']);
}

public function validation()
{
    if($this->email !== null) {
        $this->validate(
            new Email(
                array(
                    'field'    => 'email',
                    'required' => true,
                )
            )
        );
        if ($this->validationHasFailed() == true) {
            return false;
        }
    }
}

You do want errors of "something is required". All you're missing are just proper implementations of defaults over models. Once you get used to those mechanics, you should find them easy to handle and with more pros than cons.

2
AsConfused On

What you are doing is called an insert. To set a column to a different value in a pre-existing row is called an update.

The latter is flexible, the former in not.

I highly recommend not treating a database like this is what i feel like

Put all the data in. Null is your enemy