3

This is a question about "best practise". I've taken over a project which I'm working on right now, and the custom modules this project comes with all access fields defined through the UI. In other words, the field names are "hard coded" in code - even though the fields are not defined in code. Is this alright?

I'm thinking that the code depends on data (in fields) which it has no guarantee will be there. Anyone could delete the fields at any time.

If you need to access fields from code, how do you make sure that the fields exist? Do you make sure that the modules define the field (programatically)?

  • Great question. I think you'll encounter lots of situations where you'll need to do this and you may never be 100% comfortable with the solutions. Use features and disable the UI in production, that should alleviate a lot of your concerns. – Charlie Schliesser Nov 1 '14 at 15:21
-1

I usually use the entity_metadata_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.

To see if a field exists, you don't need a wrapper. You can use:

if ($node->my_field) {
...
}

You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.

  • 1
    Thanks for your input. Even though you can check whether fields exist, is that really a good way to do it? If your'e setting up a new site, you need to configure those fields and know how the code use them? Isn't there a coupling which is just too tight here? – sbrattla Oct 31 '14 at 20:18
  • That's not how to check if a field exists on an entity (if it doesn't you'll get errors). You should either use try...catch with a wrapper, or field_get_items if you insist on doing it procedurally. If not at the entity level, you should use field_info_field and field_info_instance to determine existence. Fields can also be programmatically locked so they can't be deleted through the UI – Clive Nov 1 '14 at 10:00
  • @Clive : I'm thinking of doing something in the style of "locking" the fields, and I was thinking of using the Features module to do this. Modules which access fields defined in the UI could have a dependency on the configuration module produced by Features. That way, fields are locked and the modules depending on the (UI defined) fields have a declared dependency on the configuration module (which now "owns" the fields in question). I'm thinking that this could be a robust way to go about this. – sbrattla Nov 1 '14 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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