0

For a site I am working on I am using the address field. Each node can have multiple addresses and at least one is required. All the addresses are in the US so I set the default to the US.

When the user enters and address a new field shows up with the default country address. Whenever the go to edit the page a new one with just the country is also their. They save and soon there is a bunch of addresses with only a country. This causes other parts of the site to break.

I need a way to either make the default in the form none or to delete addresses that have only a country when the node is saved/updated.

I didn't have luck with either but admitably I am new to using hooks. Below is my most recent attempt by using the node presave hook.

function postal_default_node_presave($node) {
  if ($node->type == 'micro_property') {
    foreach($node->field_micro_address[LANGUAGE_NONE] as $address){
        dpm($address);
        unset($address['country']);
        unset($address['element_key']);
        $found = false;
        // Cycles all submitted address field components for the country to see if any have been filled
        foreach ($address as $value) {
            if (!empty($value) > 0) { $found = true; }
        }
        // Empty the address and location arrays if the fields were blank
        if (!$found) {
            dpm('not found reseting');
            $node->field_address = array();
            $node->field_location = array();
        }
    }
    return $node;
  }
}

The dpm messages are posting what I would expect but the node being saved is not.

2 Answers 2

1

I was on the right track and made a really stupid mistake and don't know why I didn't notice it. I was deleting the correct way but I was deleting the wrong thing. I was in a loop since there are multiple addresses.

// Empty the address and location arrays if the fields were blank
if (!$found) {
    unset($node->field_micro_address[LANGUAGE_NONE][$k]);
}
0

I think the code to delete the fields content is wrong. Have a look at: http://fooninja.net/2011/06/06/updating-nodes-programmatically-in-drupal-7/

In that blog post they use unset():

// Delete field with index 0
unset($node->field_textfoo[$node->language][0]);

// Delete third field from a multi-value field
unset($node->field_textfoo[$node->language][2]);

// Delete whole field (if field is multi-value, all values are deleted)
unset($node->field_textfoo[$node->language]);
1
  • unset should work just the same as an empty array although null !== array drupal doesn't check. the real issue was that I wasn't deleting the right var.
    – rparker
    Commented Mar 12, 2014 at 1:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.