Problem/Motivation

I created a node with a PER field, and set two values on it.

In PHP code, I load the node and iterate the field like this:

    foreach ($node->field_test_per as $value) {
      dsm($value);
    }

This outputs 3 items, instead of the expected 2.

The last item has 'target_id' of 0 and primary of 0.

This is stored in the DB too. I can reproduce this by saving a host node with the checkboxes widget -- a DB row is made in the field table for EVERY item in the widget, not just the selected ones.

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

joachim created an issue. See original summary.

joachim’s picture

Title: iterating over field item list produces an extra empty item » checkboxes widget saves extra empty items in the DB
Issue summary: View changes
bluegeek9’s picture

Assigned: Unassigned » bluegeek9

  • bluegeek9 committed 3dde86c0 on 1.0.x
    feat: #3571301 checkboxes widget saves extra empty items in the DB
    
bluegeek9’s picture

Assigned: bluegeek9 » Unassigned
Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

joachim’s picture

Thanks for the quick fix!

if (!isset($value['target_id']) || (string) $value['target_id'] === '' || (int) $value['target_id'] === 0) {

This line would be a lot simpler as a check for empty().

joachim’s picture

Also, I don't think there's a case where you'd get a value of 0 for the entity ID?

bluegeek9 changed the visibility of the branch 1.0.x to hidden.

bluegeek9’s picture

I guess when it is blank.

$value['target_id']= '';
echo (int) $value['target_id'];
> 0

  • bluegeek9 committed a552633b on 1.0.x
    feat: #3571301 checkboxes widget saves extra empty items in the DB
    
joachim’s picture

The case $value['target_id']= ''; was already covered by the cast to (string).

Can I ask if you're using an LLM for working on this module's code?

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.