PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] How to Save HasAndBelongsToMany (habtm) data when empty in CakePHP

 April 22, 2022     cakephp, cakephp-2.3, has-and-belongs-to-many, save     No comments   

Issue

I have a hasAndBelongsToMany association between Node and NodeTag.

My save works great when at least one is selected, but - if there is a previous association, and they try to save with none selected, my habtm table doesn't get updated, since it's not getting anything passed for NodeTag.

(I'm not sure if this is because I'm using javascript and custom buttons, or if the default CakePHP checkboxes do the same thing).


Solution

In my Controller, before the save, I added this:

if(!isset($this->request->data['NodeTag'])) {
    $this->request->data['NodeTag'][0] = array();
}

This makes it so if I wasn't sending any NodeTag data, I now pass an empty array, and it updates the habtm table so that this Node no longer has any rows for NodeTags.

Note: Notice the array structure: ['NodeTag'][0] = array();



Answered By - Dave
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing