Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Check if a data already exists in the table.

Check if a data already exists in the table.

I want to add a function and my model to validate whether a data exists or not. I did est function

    public function beforeSave(){

         $valor = SpmContacto::findFirstByCONT_CEDULA($this->CONT_CEDULA);
         if (!$valor) {
            return TRUE;
            }else{
             echo "Couldn't find your data. What's up?";
             return FALSE;
         }
     }

But this function does not work. It left me a blank screen. Could you be because apart from a BeforeSave function, I already have a BeforeCreate function?

Blank screen means you got exception. Check logs.



34.2k

But the function if this correct?



46.5k
Accepted
answer
edited May '16

I don't think so.

  • you should really check your logs, and possible thrown exceptions. Blank page comes with an HTTP status 500 I guess.
  • hitting RDBMS to check whenever data already exist before saving, is a bad approach / practise. If you need such type of constraint (i.e. you want to make sure that certain field in a table is UNIQUE), you just ADD UNIQUE INDEX on top of RDBMS, and you're done. In other words, this task should be handled at a RDBMS level, not ORM/Model/Application. Yeah, I'm old school with this, but...
  • if you really want to handle it via ORM / application level then you can use Phalcon's Uniqueness special “validation” event.

Additionally, what you basically want with beforeSave() event in Model is:

public function beforeSave()
    {
        if ($this->year < 0) {
            echo "Year cannot be smaller than zero!";
            return false;
        }

You see, only a portion of business logic is there - your model object is created at runtime, and thus is being checked before actual save (insert/update) will ever touch your RDBMS.



34.2k

Yes, I added it in the beforeSave event, but I have more things in this event, more functions and so wanted to use another event not the same

So create eventmanager, you can add there as many methods you want etc etc.



46.9k

I suspect that findFirstByCONT_CEDULA isn't correct.