Sunday, July 27, 2014

Re: Behavior method won't work

Apologies, my example should say if(! $this->Attraction->isDeleted($id)) to match the flash message.


On 27 July 2014 11:36, Stephen S <hellospeakman@gmail.com> wrote:
You can create a custom app model method to overcome this, something like this:

public function isDeleted($recordId) {
    if(! $this->exists($recordId)) {
        return true;
    }

    if(! $this->hasField('deleted')) {
         return false;
    }

    $record = $this->find('count', array(
        'conditions' => array(
            "{$this->alias}.id" => $recordId,
            'NOT' => array("{$this->alias}.deleted' => null)
        )
    );

    return ($record > 0) ? true : false; 
}

Then within your controller, something like this:

$this->Attraction->delete($id);
if($this->Attraction->isDeleted($id)) {
    $this->Session->setFlash(__('Attraction could not be deleted'));
}

All the model method will do is check if the row doesn't exist (true, hard delete), if it does exist and doesn't have the deleted field then soft delete isn't possible so false it isn't deleted, otherwise count if the record exists with deleted not set to null and return true or false based on the result.

This is the main issue with using $this->Model->delete() for both soft and hard delete, if you created your own method like $this->Model->detectAndDelete() which deletes using the appropriate method by checking hasField('deleted') you wouldn't need the new model check.

Anyhow I hope this helps.


On 27 July 2014 11:22, Sam Clauw <info@bellewaerdefun.be> wrote:
Allright, I should know that, you're totally right! It works for my now, except my flash error of course. I could put it outside the if ($this->Attraction->delete($id)) {} check, but then the flash would always been shown, even if there was no delete...

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.



--
Kind Regards
 Stephen Speakman



--
Kind Regards
 Stephen Speakman

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: