views:

146

answers:

3
public $form = array (  
    array(  
        'field' => 'email',  
        'params' => array(  
            array(  
                'rule' => 'email',  
                'on' => 'create',  
                'required' => true,  
                'error' => 'The email is invalid!'  
            ),  
            array(  
                'rule' => 'email',  
                'on' => 'update',  
                'required' => false,  
                'error' => 'The email is invalid!'  
            )  
        )  
    )  
);


public function onlyNeeded($action) {
    $form = $this->form;
    $action = $this->action;

    foreach ($form as $formelement) {
        $field = $formelement['field'];
        $paramsgroup = $formelement['params'];
        if ($paramsgroup['on'] != $action) {
            form = removeparamsgroup($form, $action);
            }
        }
    return $form;
}

How do I do the removeparamsgroup() function?

There are [index]es, not only [name]s!

Do you know what I mean?

array(array( twice!

A: 

unset($form['params']) ? What do you mean by remove?

jmucchiello
Ya i'm lost too. I don't understand the question.
gradbot
when the 'action' = create, param arrays with 'on' = 'update' should be deleted from the form arrayarray( 'rule' => 'email', 'on' => 'update', 'required' => false, 'error' => 'The email is invalid!' )
Delirium tremens
I've just tried $form = unset($paramsgroup), but then my IDE highlited unset as an error!
Delirium tremens
Maybe, I should call it param*sub*group.
Delirium tremens
+1  A: 

If you get the array key in the foreach loop, you can unset the correct array index using using that. You also need to loop over each param of each form element, which you weren't doing in your example.

public function onlyNeeded($action) {
    $form = $this->form;

    //get $formelement by reference so it can be modified
    foreach ($form as & $formelement) {

        //$key becomes the index of current $param in $formelement['params']
        foreach ($formelement['params'] as $key => $param) {
           if ($param['on'] != $action) {
               unset($formelement['params'][$key]);
           }
        }
    }
    return $form;
}
Tom Haigh
nice job, you beat me too it ;)
gradbot
A: 

Try this.

function onlyNeeded($action) {
    $form = $this->form;

    foreach ($form as &$formelement) {
        foreach ($formelement['params'] as $key => $paramsgroup)
        {
            if ($paramsgroup['on'] != $action)
                unset($formelement['params'][$key]);
        }
    }
    return $form;
}

Don't forget the & sign in the first foreach loop or it won't work. Without the & sign foreach copies each element instead of returning a reference.

gradbot