[Solved] How would I enable a behavior on a content type only for Plone 6 ("plone.textindexer")

An add-on has a behavior that adds extra fields. These fields should be searchable.
In Plone 5 this is done with

from collective import dexteritytextindexer as textindexer
textindexer.searchable("foo")

Therefore the behavior collective.dexteritytextindexer needs to be added in
/profiles/types/mycontenttype.xml

In Plone 6 instead plone.textindexer.

So, how do you use behaviors conditionally?
What's the recommended way, programmatically?

Try something like the following:

In the zcml where your behaviorpackage is included:

<include zcml:condition="have plone-6" package=".behaviorpackage" />

and in your code use:

from plone.app.dexterity import textindexer
...
textindexer.searchable("foo")

Plone seems to be forgiving. Pretending that both, Plone 5 behavior and Plone 6 behavior, should be enabled, Plone runs fine and does what it should. The additional fields are added to the content type instances.

  <!-- Enabled behaviors -->
  <property name="behaviors" purge="false">
      …
      <element value="collective.dexteritytextindexer" />
      <element value="plone.textindexer" />
  </property>

With conditional imports, everything is OK. The add-on is fit for Plone 5 and Plone 6.

try:
    from plone.app.dexterity import textindexer
except ImportError:
    from collective import dexteritytextindexer as textindexer

textindexer.searchable("organisation")

Sometimes life is easy…

For the meticulous: Consider what could happen when - for whatever reason - both libraries are installed in the environment. This usually should not happen. But it might be the case. :wink:

One could check the version of a known and always installed package (e.g. Products.CMFPlone):

import Products.CMFPlone
from importlib.metadata import version
major_version = version('Products.CMFPlone').split('.')[0]
if major_version == 6:
    from plone.app.dexterity import textindexer
elif major_version == 5:
    from collective import dexteritytextindexer as textindexer
else:
    raise Exception("...") # <- raise exception if needed

This needs Python >= 3.8!

If you run Plone 6 (which usually has not collective.dexteritytextindexer installed) you'll get the following error when you install your addon:

ERROR   [plone.dexterity.schema:186][waitress-3] Error resolving behavior collective.dexteritytextindexer