1

I can't seem to figure out a good way to see if an Entry has an actual field defined. All the examples I see just to a falsy check for the property name, but this might fail if you have previously defined a field (either by switching Entry Type, or if you modified the Entry Type).

Example:

Entry Type 1 previously had a field called MyFirstField (let's say it's a static table).

I later on concludes that the table was wrong, and hard to work with on some types. So I modify the Entry Type and replace it with MyFirstFieldV2. I still keep MyFirstField on some other type, and I use a shared partial to render this, so I want to check if the current type has MyFirstField, or MyFirstFieldV2 and render it appropriately.

The falsy check works, as long as it is a new entry. If it is an old entry, it will think that it has data for MyFirstField, even though I have removed that field from the type.

Entry type has a fields() method, that returns an array of all fields, but that becomes quite clunky to work with. I guess it would be possible to make some helper that validates the field name against that array, but it feels like there should be an easier way.

Preferably I think the entry should loose all properties that no longer exists on the entry type, but it seems like every entry has a property (albeit null) for each and every field that exists in the system?

EDIT: Regardless whether this is a feature or a bug, what is the appropriate way to check if an Entry Type has a certain field configured? The fields() function doesn't at all return what I expected.

5
  • I agree that it's not intuitive that when removing a field from an entry type the data does not get deleted, but personally I view this as a feature rather than a bug. For example it allows for switching between (some) fieldtypes without losing data - If you create something as a Redactor field and later decide it should be a simple text input you can switch back without losing any data thanks to this feature. The only real 'solution' to your problem is to put the old field back into the entry type and then delete the content from it. Feb 27 '20 at 12:46
  • @JamesSmith Sure, having the data intact when switching back is indeed nice, but I'm talking about having the data at hand, when rendering the template. That could be avoidable (filtering out fields that no longer exists).
    – jishi
    Feb 27 '20 at 14:21
  • Looks like refactoring this behaviour has been on the radar for at least 3 years: github.com/craftcms/cms/issues/1524 (github.com/craftcms/cms/issues/1898) Feb 28 '20 at 11:17
  • Targeted for 4.0, that is exciting news, thank you for providing these links!
    – jishi
    Feb 28 '20 at 11:44
  • Seems to be targeted for 5.0 now... :(
    – jishi
    Sep 2 '20 at 10:54

Your Answer

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

Browse other questions tagged or ask your own question.