<?php
namespace MyCustomFieldNotifier\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\Context;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\Framework\Api\Event\SearchCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use src\Core\Content\Cms\CmsPageEvents;
use src\Core\Content\Cms\Events\CmsPageLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchedEvent;
use Shopware\Core\Checkout\Order\OrderDefinition;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchRequestEvent;
use Shopware\Core\System\Tag\Aggregate\TagEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
class OrderCustomFieldChangeSubscriber implements EventSubscriberInterface
{
private MailerInterface $mailer;
private LoggerInterface $logger;
private EntityRepositoryInterface $orderRepository;
private RequestStack $requestStack;
private SystemConfigService $configService;
private EntityRepository $userRepository;
public function __construct(
MailerInterface $mailer,
LoggerInterface $logger,
EntityRepositoryInterface $orderRepository,
RequestStack $requestStack,
RouterInterface $router,
SystemConfigService $configService,
EntityRepository $userRepository
) {
$this->mailer = $mailer;
$this->logger = $logger;
$this->orderRepository = $orderRepository;
$this->requestStack = $requestStack;
$this->router = $router;
$this->configService = $configService;
$this->userRepository = $userRepository;
}
public static function getSubscribedEvents(): array
{
return [
'order.written' => 'onOrderWritten',
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced',
CartConvertedEvent::class => 'addCustomFieldsToOrder',
GenericPageLoadedEvent::class => 'onGenericPageLoaded',
SearchCriteriaEvent::class => 'onSearchCriteria',
'cms_page.loaded' => 'onCMSPageLoaded',
EntitySearchedEvent::class => 'onEntitySearched',
'order.search.request' => 'onOrderSearchRequest',
];
}
// NEW START
// public function onOrderWritten(EntityWrittenEvent $event): void
// {
// $this->logger->info('TEST23 ENTERED onOrderWritten()');
// foreach ($event->getWriteResults() as $writeResult) {
// $payload = $writeResult->getPayload();
// $this->logger->info('TEST23 ENTERED foreach ($event->getWriteResults()');
// $payloadString = print_r($payload, true);
// $this->logger->info('TEST234 $writeResult->getPayload() {payloadString}', [
// 'payloadString' => $payloadString,
// ]);
// if ($writeResult->getChangeSet()) {
// $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSetString}', [
// 'changeSetString' => $writeResult->getChangeSet(),
// ]);
// } else {
// $this->logger->info('TEST234 ChangeSet IS EMPTY');
// }
// // Check if the custom field is present in the payload
// if (isset($payload['customFields']['custom_downloads_testfield'])) {
// $newValue = $payload['customFields']['custom_downloads_testfield'];
// // Get the changeset to compare old and new values
// $changeSet = $writeResult->getChangeSet();
// // if ( !$changeSet ) {$this->logger->info('TEST234 CHANGESET is EMPTY');}
// $changeSetString = print_r($changeSet, true);
// $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSetString}', [
// 'changeSetString' => $changeSetString,
// ]);
// $this->logger->info('TEST234 $writeResult->getChangeSet(): {changeSet}', [
// 'changeSet' => $changeSet,
// ]);
// if ($changeSet) {
// $this->logger->info('ChangeSet detected');
// $oldValue = $changeSet->getBefore('customFields')['custom_downloads_testfield'] ?? null;
// if ($oldValue !== $newValue) {
// // Custom field value has actually changed
// $this->logger->info('TEST23 Custom field updated', [
// 'oldValue' => $oldValue,
// 'newValue' => $newValue,
// ]);
// // Send an email to the customer (for demonstration purposes, using dummy email)
// $email = (new Email())
// ->from('noreply@comentire.de')
// ->to('szymanski@comentire.de') // Replace with actual customer email
// ->subject('Your order has been updated')
// ->text(sprintf(
// 'Dear customer,
// Your order custom field "custom_downloads_testfield" has been updated.
// Old Value: %s
// New Value: %s
// Thank you for your business!
// Best regards,
// Your Company',
// $oldValue,
// $newValue
// ));
// $this->mailer->send($email);
// }
// }
// }
// }
// }
// NEW END
// OLD START
public function onOrderWritten(EntityWrittenEvent $event): void
{
$this->logger->info('TEST23 ENTERED onOrderWritten() TEST24TEST24TEST24TEST24TEST24TEST24');
$this->logger->info('TEST23 ENTERED onOrderWritten()');
foreach ($event->getPayloads() as $payload) {
if ((isset($payload['customFields']['custom_downloads_download_1']) || isset($payload['customFields']['custom_downloads_download_2'])) && isset($payload['updatedById'])) {
$orderId = $payload['id'];
// $this->logger->info('TEST23 Order custom field change detected', [
// 'customFieldName' => 'custom_downloads_testfield',
// 'newValue' => $payload['customFields']['custom_downloads_testfield'],
// 'orderId' => $orderId,
// ]);
// Fetch the order to get customer data
$criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
$criteria->addAssociation('orderCustomer'); // Load customer data
$order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();
if ($order) {
$customerEmail = $order->getOrderCustomer()->getEmail();
$orderNumber = $order->getOrderNumber(); // Retrieve the order number
// $url = $this->router->generate('frontend.account.order.page', ['orderNumber' => $orderNumber], RouterInterface::ABSOLUTE_URL);
$this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
$deepLinkCode = $order->getDeepLinkCode();
$url = $this->router->generate(
'frontend.account.order.page',
[],
RouterInterface::ABSOLUTE_URL
);
$url .= "/" . $deepLinkCode;
$email = (new Email())
->from('noreply@sw6afg.ce1.eu')
->to($customerEmail)
->subject('New document available')
->text(sprintf(
'Hello %s %s,
New documents have been added to your orders / ordered products.
The download section in your order (Order Number: %s) was changed.
Please log in to retrieve them:
%s
You can check your order status at any time in your account under “Orders”.
If you have any questions, please do not hesitate to contact us.
With kind regards,
Your AUTOFLUG FLYWEIGHT® Team',
$order->getOrderCustomer()->getFirstName(),
$order->getOrderCustomer()->getLastName(),
$orderNumber,
$url,
));
// Convert payload to a readable format
$payloadString = print_r($payload, true);
$this->mailer->send($email);
$email = (new Email())
->from('noreply@comentire.de')
->addTo('szymanski@comentire.de')
->subject('Order Custom Field Updated')
->text(sprintf(
'FOR USER: %s ORDER NUMBER: %s A custom field in your order was updated. PAYLOAD: %s',
$customerEmail,
$orderNumber,
$payloadString
));
$this->mailer->send($email);
} else {
$this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
}
}
// if (isset($payload['customFields']['custom_downloads_download_1']) && isset($payload['updatedById'])) {
// $orderId = $payload['id'];
// $this->logger->info('TEST23 Order custom field change detected', [
// 'customFieldName' => 'custom_downloads_testfield',
// 'newValue' => $payload['customFields']['custom_downloads_download_1'],
// 'orderId' => $orderId,
// ]);
// // Fetch the order to get customer data
// $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
// $criteria->addAssociation('orderCustomer'); // Load customer data
// $order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();
// if ($order) {
// $customerEmail = $order->getOrderCustomer()->getEmail();
// $orderNumber = $order->getOrderNumber(); // Retrieve the order number
// $this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
// $email = (new Email())
// ->from('noreply@comentire.de')
// ->to($customerEmail)
// ->subject('Order Custom Field Updated')
// ->text(sprintf(
// 'Dear customer,',
// $orderNumber,
// 'custom_downloads_download_1',
// $payload['customFields']['custom_downloads_download_1']
// ));
// // Convert payload to a readable format
// $payloadString = print_r($payload, true);
// $this->mailer->send($email);
// $email = (new Email())
// ->from('noreply@comentire.de')
// ->addTo('szymanski@comentire.de')
// ->subject('Order Custom Field Updated')
// ->text(sprintf(
// 'FOR USER: %s ORDER NUMBER: %s The custom field "%s" in your order was updated. New value: %s PAYLOAD: %s',
// $customerEmail,
// $orderNumber,
// 'custom_downloads_download_1',
// $payload['customFields']['custom_downloads_download_1'],
// $payloadString
// ));
// $this->mailer->send($email);
// } else {
// $this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
// }
// }
// if (isset($payload['customFields']['custom_downloads_download_2']) && isset($payload['updatedById'])) {
// $orderId = $payload['id'];
// $this->logger->info('TEST23 Order custom field change detected', [
// 'customFieldName' => 'custom_downloads_download_2',
// 'newValue' => $payload['customFields']['custom_downloads_download_2'],
// 'orderId' => $orderId,
// ]);
// // Fetch the order to get customer data
// $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$orderId]);
// $criteria->addAssociation('orderCustomer'); // Load customer data
// $order = $this->orderRepository->search($criteria, Context::createDefaultContext())->first();
// if ($order) {
// $customerEmail = $order->getOrderCustomer()->getEmail();
// $orderNumber = $order->getOrderNumber(); // Retrieve the order number
// $this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
// $email = (new Email())
// ->from('noreply@comentire.de')
// ->to($customerEmail)
// ->subject('Order Custom Field Updated')
// ->text(sprintf(
// 'Dear customer,',
// $orderNumber,
// 'custom_downloads_download_2',
// $payload['customFields']['custom_downloads_download_2']
// ));
// // Convert payload to a readable format
// $payloadString = print_r($payload, true);
// $this->mailer->send($email);
// $email = (new Email())
// ->from('noreply@comentire.de')
// ->addTo('szymanski@comentire.de')
// ->subject('Order Custom Field Updated')
// ->text(sprintf(
// 'FOR USER: %s ORDER NUMBER: %s The custom field "%s" in your order was updated. New value: %s PAYLOAD: %s',
// $customerEmail,
// $orderNumber,
// 'custom_downloads_download_2',
// $payload['customFields']['custom_downloads_download_2'],
// $payloadString
// ));
// $this->mailer->send($email);
// } else {
// $this->logger->warning('Order not found for ID', ['orderId' => $orderId]);
// }
// }
}
}
// OLD END
public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
$this->logger->info('TEST233 ENTERED onCheckoutOrderPlaced()');
// FIRST TRY START //
// $order = $event->getOrder();
// $customFields = $event->getContext()->getRequestDataBag()->get('customFields');
// if (!empty($customFields['custom_order_fields_customer_reference_ID'])) {
// $this->orderRepository->update([
// [
// 'id' => $order->getId(),
// 'customFields' => [
// 'custom_order_fields_customer_reference_ID' => $customFields['custom_order_fields_customer_reference_ID']
// ],
// ],
// ], $event->getContext());
// }
// FIRST TRY END //
// SECOND TRY START //
// $orderId = $event->getOrderId();
// $context = $event->getContext();
// // Fetch the order using its ID
// $criteria = new Criteria([$orderId]);
// $order = $this->orderRepository->search($criteria, $context)->first();
// if (!$order) {
// return;
// }
// // Get custom field data from request
// $customFields = $event->getContext()->getRequestDataBag()->get('customFields');
// if (!empty($customFields['custom_order_fields_customer_reference_ID'])) {
// $this->orderRepository->update([
// [
// 'id' => $orderId,
// 'customFields' => array_merge($order->getCustomFields() ?? [], [
// 'custom_order_fields_customer_reference_ID' => $customFields['custom_order_fields_customer_reference_ID']
// ]),
// ],
// ], $context);
// }
// SECOND TRY END //
$orderId = $event->getOrderId();
$context = $event->getContext();
// Fetch the order using its ID
$criteria = new Criteria([$orderId]);
$criteria->addAssociation('orderCustomer'); // Ensure order data is fully loaded
$order = $this->orderRepository->search($criteria, $context)->first();
if (!$order) {
return;
}
// Retrieve existing custom fields
$existingCustomFields = $order->getCustomFields() ?? [];
if ($order->getCustomFields()) {
$this->logger->info('TEST233 FOUND $order->getCustomFields()', ['$order->getCustomFields()' => $order->getCustomFields()]);
//$this->logger->info('TEST23 Customer email found for order', ['email' => $customerEmail]);
}
else {
$this->logger->info('TEST233 NOT FOUND $order->getCustomFields()');
}
if ($order) {
$this->logger->info('TEST233 FOUND $order', ['$order' => $order]);
}
else {
$this->logger->info('TEST233 NOT FOUND $order');
}
// Ensure the field exists before modifying
// if (!isset($existingCustomFields['custom_order_fields_customer_reference_ID'])) {
// return;
// }
// else {
// $this->logger->info('TEST23 FOUND custom_order_fields_customer_reference_ID found');
// }
// // Example: Modify the custom field (if needed)
// $existingCustomFields['custom_order_fields_customer_reference_ID'] .= ' - Processed';
//TODO DELETE THIS START
// foreach ($event->getPayloads() as $payload) {
// if ( isset($payload['customFields']['custom_order_fields_customer_reference_ID']) ) {
// $this->logger->info('TEST233 FOUND custom_order_fields_customer_reference_ID');
// }
// }
$this->logger->info('TEST233 EVENT: ', ['$event->getOrder()' => $event->getOrder()] );
$this->logger->info('TEST233 EVENT: ', ['$event->getAvailableData()' => $event->getAvailableData()] );
$this->logger->info('TEST233 EVENT: ', ['$event->getContext()' => $event->getContext()] );
$existingCustomFields = [
"foo" => "bar",
"bar" => "foo",
"custom_order_fields_customer_reference_ID" => "#TEST@@@2324",
];
//TODO DELETE THIS END
// // Update the order with the modified custom field
// $this->orderRepository->update([
// [
// 'id' => $orderId,
// 'customFields' => $existingCustomFields,
// ],
// ], $context);
$this->logger->info('TEST233 FOUND $order', ['$order' => $order]);
$this->logger->info('TEST233 FOUND $order', ['$order' => $this->orderRepository->search($criteria, $context)->first()]);
}
public function addCustomFieldsToOrder(CartConvertedEvent $event): void
{
$this->logger->info('Subscriber triggered: ');
dump('Subscriber triggered: ');
$orderData = $event->getConvertedCart();
$orderCustomFields = $orderData['customFields'] ?? [];
$customerReferenceID = $this->requestStack->getCurrentRequest()->request->get('custom_order_fields_customer_reference_ID');
if ($customerReferenceID) {
$orderCustomFields['custom_order_fields_customer_reference_ID'] = $customerReferenceID;
}
$orderData['customFields'] = $orderCustomFields;
// $customerReferenceID = $this->requestStack->getCurrentRequest()->request->get('custom_order_fields_comment');
// if ($customerReferenceID) {
// $orderCustomFields['custom_order_fields_test_textarea'] = $customerReferenceID;
// }
// $orderData['customFields'] = $orderCustomFields;
$event->setConvertedCart($orderData);
}
// make basicInformation.email accessible in the frontend
public function onGenericPageLoaded(GenericPageLoadedEvent $event): void
{
$this->logger->info( 'Subscriber triggered: onGenericPageLoaded() ');
$salesChannelId = $event->getSalesChannelContext()->getSalesChannelId();
$email = $this->configService->get('core.basicInformation.email', $salesChannelId);
$event->getPage()->addExtension('shopEmail', new ArrayStruct([
'email' => $email
]));
}
public function onOrderSearchRequest(EntitySearchRequestEvent $event): void
{
$this->logger->info( 'Subscriber triggered: onOrderSearchRequest() ');
$request = $this->requestStack->getCurrentRequest();
$context = $request->attributes->get('sw-context');
$source = $context->getSource();
if (!$source || $source->getType() !== 'admin') {
return;
}
$user = $source->getUser();
if (!$user) {
return;
}
// Check for a specific ACL role
$hasRole = false;
foreach ($user->getAclRoles()->getElements() ?? [] as $role) {
if ($role->getName() === 'testFirma-MRO') {
$hasRole = true;
break;
}
}
if (!$hasRole) {
return;
}
// Apply filter: orders where customer has tag "VIP"
$criteria = $event->getCriteria();
// Add customer and tags associations
$criteria->addAssociation('orderCustomer.customer.tags');
// Filter by customer tag name (make sure it matches exactly)
$criteria->addFilter(
new EqualsFilter('orderCustomer.customer.tags.name', 'testFirma-mro-visible')
);
}
public function onSearchCriteria(SearchCriteriaEvent $event): void
{
$this->logger->info( 'Subscriber triggered: onSearchCriteria() ');
// Only act on the "order" entity
if ($event->getDefinition()->getEntityName() !== 'order') {
return;
}
$context = $event->getContext();
$source = $context->getSource();
if ($source->getType() !== 'admin') {
return;
}
$user = $source->getUser();
if (!$user) {
return;
}
// Check if the user has the specific role
$hasRole = false;
$aclRoles = $user->getAclRoles();
if ($aclRoles !== null) {
foreach ($aclRoles->getElements() as $role) {
if ($role->getName() === 'order_view_customer_tag_vip') {
$hasRole = true;
break;
}
}
}
if (!$hasRole) {
return;
}
// Apply filter: only show orders where customer has tag "VIP"
$criteria = $event->getCriteria();
// Include the customer tag association
$criteria->addAssociation('orderCustomer.customer.tags');
// Filter orders by customer tag
$criteria->addFilter(
new EqualsFilter('orderCustomer.customer.tags.name', 'VIP')
);
}
public function onCMSPageLoaded(): void
{
$this->logger->info( 'Subscriber triggered: onCMSPageLoaded() ');
}
public function onEntitySearched(EntitySearchedEvent $event): void
{
$this->logger->info( 'Subscriber triggered: onEntitySearched() ');
// Only act on orders
if (!$event->getDefinition() instanceof OrderDefinition) {
return;
}
$context = $event->getContext();
$source = $context->getSource();
// Only apply in Admin API
if (!$source instanceof AdminApiSource) {
return;
}
$userId = $source->getUserId();
if (!$userId) {
return;
}
// Load user with ACL roles
$criteria = new Criteria([$userId]);
$criteria->addAssociation('aclRoles');
/** @var \Shopware\Core\System\User\UserEntity|null $user */
$user = $this->userRepository->search($criteria, $context)->first();
if (!$user) {
return;
}
// // Check for specific role
// $hasRole = false;
// $aclRoles = $user->getAclRoles();
// if ($aclRoles !== null) {
// foreach ($aclRoles->getElements() as $role) {
// if ($role->getName() === 'testFirma-MRO') {
// $hasRole = true;
// break;
// }
// }
// }
// if (!$hasRole) {
// return;
// }
// // Correct way: add filter to criteria!
// $criteria = $event->getCriteria();
// // Example filter: orders whose customers have tag 'VIP'
// // Here you would need to filter by customer tag, but customer tags are in a related entity
// // so you'll need an association filter (multi-level filter), something like this:
// $criteria->addAssociation('orderCustomer.customer.tags');
// $criteria->addFilter(
// new EqualsFilter('orderCustomer.customer.tags.name', 'testFirma-mro-visible')
// );
$aclRoles = $user->getAclRoles();
if (!$aclRoles) {
return;
}
$hasMroRole = false;
$tagNamesToShare = [];
foreach ($aclRoles->getElements() as $role) {
$roleName = $role->getName();
if ($roleName === 'MRO') {
$hasMroRole = true;
}
if (str_starts_with($roleName, 'share-tag-')) {
// Extract tag name and add to list
$tagName = substr($roleName, strlen('share-tag-'));
$tagNamesToShare[] = $tagName;
}
}
$this->logger->info('TEST233 FOUND $tagNamesToShare[] = ', ['$tagNamesToShare' => $tagNamesToShare]);
// Must have both: MRO role and at least one share-tag role
if (!$hasMroRole || empty($tagNamesToShare)) {
return;
}
// ✅ Filter orders: customer must have any of the tags in $tagNamesToShare
$criteria = $event->getCriteria();
// Make sure we load customer tags in this search
$criteria->addAssociation('orderCustomer.customer.tags');
// Add filter: orders where customer has any of the allowed tags
$criteria->addFilter(
new EqualsAnyFilter('orderCustomer.customer.tags.name', $tagNamesToShare)
);
// OLD 2
// // Filter orders: Only include orders where customer has tag "VIP"
// $filtered = $event->getEntities()->filter(function ($order) {
// $orderCustomer = $order->getOrderCustomer();
// if (!$orderCustomer) {
// return false;
// }
// $customer = $orderCustomer->getCustomer();
// if (!$customer) {
// return false;
// }
// $tags = $customer->getTags();
// if (!$tags) {
// return false;
// }
// foreach ($tags as $tag) {
// if ($tag->getName() === 'VIP') {
// return true;
// }
// }
// return false;
// });
// // Overwrite entities with filtered ones
// $event->getEntities()->clear();
// foreach ($filtered as $entity) {
// $event->getEntities()->add($entity);
// }
// OLD
// // Only act on the "order" entity
// if (!$event->getDefinition() instanceof OrderDefinition) {
// return;
// }
// $context = $event->getContext();
// $source = $context->getSource();
// if (!$source instanceof AdminApiSource) {
// return;
// }
// $userId = $source->getUserId();
// if (!$userId) {
// return;
// }
//
// // Load user with roles
// $criteria = new \Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria([$userId]);
// $criteria->addAssociation('aclRoles');
// /** @var \Shopware\Core\System\User\UserEntity|null $user */
// $user = $this->userRepository->search($criteria, $event->getContext())->first();
// if (!$user) {
// return;
// }
// // Now you can check roles safely
// $hasRole = false;
// $aclRoles = $user->getAclRoles();
// if ($aclRoles !== null) {
// foreach ($aclRoles->getElements() as $role) {
// if ($role->getName() === 'order_view_customer_tag_vip') {
// $hasRole = true;
// break;
// }
// }
// }
// if (!$hasRole) {
// return;
// }
// // Filter out orders where the customer does NOT have tag "VIP"
// $filtered = $event->getEntities()->filter(function ($order) {
// $orderCustomer = $order->getOrderCustomer();
// if (!$orderCustomer) {
// return false;
// }
// $customer = $orderCustomer->getCustomer();
// if (!$customer) {
// return false;
// }
// $tags = $customer->getTags();
// foreach ($tags as $tag) {
// if ($tag->getName() === 'VIP') {
// return true;
// }
// }
// // If no matching tag, exclude the order
// return false;
// });
// // Override the entity result with the filtered list
// $event->getEntities()->clear();
// foreach ($filtered as $entity) {
// $event->getEntities()->add($entity);
// }
}
}