In a Shopware vue component, for the editor/designer in the administration, I got the following code to fetch data from a custom entity:
fetchTeam({ targetId }) {
this.teamRepository.get(targetId).then((team) => {
this.$set(this.element.data, 'team', team);
});
},
This almost works. E.g. It sends a HTTP request to the API and retrieves the expected data; the problem is that the data is never added to this.element.data
; The team
property is added, but it is always filled with null
as value.
I was trying to find inspiration from Shopware's own code, and they have something very similar to this, but I am not sure if I am using the code in the wrong context.
In developer tools I can see that the XHR request is performed, and it returns the expected data, so presumably this is just a minor issue.
What I want to do: My idea is this:
Rather than saving all the data in the CMS element config, I want to have it fetched from the backend when editing a page.
When saving the page with the custom CMS element on from the editor, an ID for the entity should be saved in the element config, which is used elsewhere (in the editor and storefront) to retrieve data from the entity.
Finally, in the storefront I would also re-fetch the data. I have not started this code yet, but hope it is possible.
You've got the right idea. Store the ID of the entity in your elements config and then create a CMS Element Resolver that fetches the data for your element using that ID.
class MyElementResolver extends AbstractCmsElementResolver
{
public function getType(): string
{
return 'myElementType';
}
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
$teamConfig = $slot->getFieldConfig()->get('team');
if (!$teamConfig) {
return null;
}
$teamId = $teamConfig->getValue();
$criteria = new Criteria([$teamId]);
$criteriaCollection = new CriteriaCollection();
$criteriaCollection->add('team_' . $slot->getUniqueIdentifier(), TeamDefinition::class, $criteria);
return $criteriaCollection;
}
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
$searchResult = $result->get('team_' . $slot->getUniqueIdentifier());
if (!$searchResult) {
return;
}
$teamConfig = $slot->getFieldConfig()->get('team');
$team = $searchResult->get($teamConfig->getValue());
if (!$team instanceof TeamEntity) {
return;
}
$slot->setData($team);
}
}