Henrique Ordine
Henrique Ordine

Reputation: 3337

Of which Type is my hybris model item?

In my hybris Event Listener, I have a PK of an item and not the model item yet. How can I tell the type of the item to which this PK belongs?

In the hybris wiki they give this example, so that you know that an item is of the type Product:

//The product deployment code is "1"
if (1 == pk.getTypeCode())
{
    final ProductModel product = modelService.get(pk);
    //Put your business code here
}

But I don't like the idea of hardcoding the TypeCode of the type that I want to deal with.

Upvotes: 1

Views: 4554

Answers (3)

user2093800
user2093800

Reputation: 21

Below is a sample groovy script to do this in hybris 4.x.

import de.hybris.platform.core.PK;
import de.hybris.platform.jalo.type.TypeManager; // this class is deprecated though

def pkString = 8796093054980; // PK of admin
def typeService = ctx.getBean("typeService");
def modelService= ctx.getBean("modelService");

def composedType = TypeManager.getInstance().getRootComposedType(PK.fromLong(pkString).getTypeCode());
def composedTypeModel = modelService.toModelLayer(composedType);
out.println typeService.getModelClass(composedTypeModel);

Result: class de.hybris.platform.core.model.user.UserModel

Upvotes: 1

TheOutSideBox
TheOutSideBox

Reputation: 336

HAC may be used to find the type codes for defined Types in the Hybris system:

Go to : :/hac/maintain/deployments

This will give you the following info:

  1. Typecode
  2. Table
  3. Type
  4. Extension

Upvotes: 1

Henrique Ordine
Henrique Ordine

Reputation: 3337

To not hardwire the TypeCode in your source code you have to find your item in the DB first, and then you can find out it's type in 2 different ways:

final ItemModel item = modelService.get(pk);

if (ProductModel._TYPECODE.equals(item.getItemtype()))
{
    LOG.debug("ProductModel being edited");
}

//or

if (item instanceof ProductModel) {
    LOG.debug("ProductModel being edited");
}

Although this might slow things down in an AfterSaveEvent listener, since this listener will be called for every object that is edited or created or deleted in your hybris server.

Upvotes: 2

Related Questions