tags:

views:

353

answers:

3

I have a form with a whole lot of "inventory" items, my data looks like this:

$this->data['Inventory'][#]['description']
$this->data['Inventory'][#]['quantity']
$this->data['Inventory'][#]['category_id']

the thing is I don't know how to unset $this->data['Inventory'][#] if the quatity is either 0 or NULL. I can do this easily with a single record but what is the easiest way to do it with multiple records as above?

my instinct tells me to loop through $this->data in beforeSave() and unset whatever key with and array value with value of 0 or NULL for key 'quantity', is there a better way?

A: 

This should do it:

$this->data = array_filter($this->data);

EDIT: Oops, sorry this doesn't solve your problem. I think you're right, I would probably loop through the array and check the values of quantity.

Alix Axel
FYI, CakePHP offers a slightly customised version of this in its Set::filter() method (http://code.cakephp.org/source/cake/libs/set.php#66)
deizel
A: 

I wrote a Nullable behavior a while back that may do just what you're looking to do. It's available on Github (http://github.com/robwilkerson/scratchpad/tree/196e8e8bdbf042f7051f29b077a34ae9265e0983/cakephp/behaviors). It's not as polished as I'd like it to be for public consumption, but it's functional. I'm using it on several projects in production.

Rob Wilkerson
ah thanks i though cake automagically did this...
bananarepub
+1  A: 

The extract method of CakePHP's core Set class allows you to filter your data quickly without having to loop through multi dimentional arrays or traverse through tree structures.

public function beforeSave($data) {
    // select only the Inventories with a quantity greater than zero
    $this->data = Set::extract('/Inventory[quantity>0]', $this->data);
    // continue with save
    return true;
}

The beforeSave filter sounds like the correct place for this logic.

deizel