2

I have a problem, right now Im using this foreach loop on CakePhp on which I want to add all the values which are still not on the table for the respecting user. To give a little more context, the user has a menu. And the admin can select which one to add for the user to use. On the next code I receive a array with the menus which will be added as so:

//This is what comes on the ['UserMenuAccessibility'] array:
    Array ( [menu_accessibility_id2] => 2 [menu_accessibility_id3] => 3 [menu_accessibility_id4] => 4 [menu_accessibility_id5] => 5 [menu_accessibility_id8] => 8 ) 

I get the ids of the menus which want to be added to the table for the user to use. And I use the next code to add the menus to the table if they are not there still:

//I check if the array has something cause it can come with no ids.    
if (!(isset($this->request->data['UserMenuAccessibility']))) {
        $this->request->data['UserMenuAccessibility'] = array();
    }

    $UserMenuAccessibility = $this->request->data['UserMenuAccessibility'];

    foreach ($UserMenuAccessibility as $key => $value) {

        $conditions = array(
            'UserMenuAccessibility.menu_accessibility_id' => $value, 
            'UserMenuAccessibility.users_id' => $id
        );

        if ($this->User->UserMenuAccessibility->hasAny($conditions)) {

        }  else {
            $valuemenu['UserMenuAccessibility']['users_id'] = $id;
            $valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
            if ($this->User->UserMenuAccessibility->save($valuemenu)) {

            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
    }

For some reason the array is only saving the last new id which is not on the table and not the rest. For example if I have menu 1 and 2 and add 3 and 4 only 4 gets added to the table. For some reason I cant add all the missing menu ids to the table. Any ideas why this is happening?

Thanks for the help on advance.

3 Answers 3

5

It looks like your code will save each item, but each call to save() is overwriting the last entry added as $this->User->UserMenuAccessibility->id is set after the first save and will be used for subsequent saves. Try calling $this->User->UserMenuAccessibility->create() before each save to ensure that the model data is reset and ready to accept new data:-

$valuemenu['UserMenuAccessibility']['users_id'] = $id;
$valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
$this->User->UserMenuAccessibility->create();
if ($this->User->UserMenuAccessibility->save($valuemenu)) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

But of course! XD Its really weird cause I had this piece of code on another site I build. And it worked well there. I dunno why it didnt work on this side. I thank you so much for pointing that out! It work like a charm :D
1

In cakephp 2.0 $this->Model->create() create work fine. But if you are using cakephp version 3 or greater then 3. Then follow the below code

$saveData['itemId']             = 1;

$saveData['qty']                = 2;

$saveData['type']               = '0';

$saveData['status']             = 'active';

$saveData = $this->Model->newEntity($saveData);

$this->Model->save($materialmismatch);

In normal case we use patchEntity

$this->Model->patchEntity($saveData, $this->request->data);

It will only save last values of array so you have to use newEntity() with data

Comments

0

In cakephp3, patchEntity() is normally used. However, when using it for inserting-new/updating entries in a foreach loop, I too saw that it only saves the last element of the array.

What worked for me was using patchEntities(), which as explained in the patchEntity() doc, is used for patching multiple entities at once.

So simplifying and going by the original code sample to handle multiple entities, it could be:

$userMenuAccessibilityObject = TableRegistry::get('UserMenuAccessibility');
foreach ($UserMenuAccessibility as $key => $value) {
    $userMenuAccessibility = $userMenuAccessibilityObject->get($value);//get original individual entity if exists
    $userMenuAccessibilities[] = $userMenuAccessibility;
    $dataToPatch = [
        'menu_accessibility_id' => $value,
        'users_id' => $id
    ]//store corresponding entity data in array for patching after foreach
    $userMenuAccessibilitiesData[] = $dataToPatch;
}
$userMenuAccessibilities = $userMenuAccessibilityObject->patchEntities($userMenuAccessibilities, $userMenuAccessibilities);
if ($userMenuAccessibilityObject->saveMany($requisitions)) {
} else {
    $this->Session->setFlash(__('The users could not be saved. Please, try again.'));
}

Note: I haven't made it handle if entity doesn't exist, create a new one and resume. That can be done with a simple if condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.