CakePHP Code Snippet: Return only fields with values to the DB upon saving.

This code goes in {ModelName}::beforeSave:

foreach ($this->data[$this->name] as $key => $value) {
    if (!set::classicExtract($this->data,$this->name . '.' . $key)) {
        $this->data = set::remove($this->data,$this->name . '.' . $key);
    }
}

I use it where the DB may be expecting values for certain fields that are optional in the UI, and therefore may be returned empty by the controller.

CakePHP

CakePHP logo If, like me, you’re not a real PHP aficionado, you can use CakePHP to fast-track application development. Using CakePHP still requires a modicum of PHP know-how, but this can help you learn about MVC and OO PHP.

I had a look at a few different PHP MVC frameworks, and while I thought that Symfony looked the best, I ended up going with CakePHP due to hosting restrictions. CakePHP fits the bill for me due to not being able (or inclined) to change the virtual directory or install any type of URL rewriting modules.

I found that the best tutorial so far is the IBM DeveloperWorks series ‘Cook up Web sites fast with CakePHP’.

Some of the resources i’ve used so far:

I’ll post more tidbits of useful info about CakePHP and what i’ve learned here as I go.