persist example

$this->getContainer()->get('product.repository')
            ->create($products, Context::createDefaultContext());

        $cart = $this->getContainer()->get(Processor::class)->process($cart$this->salesChannelContext, new CartBehavior());

        return $cart;
    }

    private function persistCart(Cart $cart): string
    {
        $cart = $this->getContainer()->get(CartService::class)->recalculate($cart$this->salesChannelContext);
        $orderId = $this->getContainer()->get(OrderPersister::class)->persist($cart$this->salesChannelContext);

        return $orderId;
    }

    private function createCustomer(string $paymentMethodId): string
    {
        $customerId = Uuid::randomHex();
        $addressId = Uuid::randomHex();

        $customer = [
            'id' => $customerId,
            
// Encode the password with md5         if (!empty($password)) {
            $customer->setPassword($password);
        }

        if (!$customer->getNumber() && Shopware()->Config()->get('shopwareManagedCustomerNumbers')) {
            /** @var NumberRangeIncrementerInterface $incrementer */
            $incrementer = Shopware()->Container()->get(NumberRangeIncrementerInterface::class);
            $customer->setNumber((string) $incrementer->increment('user'));
        }

        $this->getManager()->persist($customer);
        $this->getManager()->flush();

        $this->View()->assign([
            'success' => true,
            'data' => $this->getCustomer($customer->getId()),
        ]);
    }

    /** * Deletes a single customer or an array of customers from the database. * Expects a single customer id or an array of customer ids which placed in the parameter customers */
public function __construct(ModelManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function addProductDetail(OrderDetail $detail): void
    {
        $product = $this->getProductFromDetail($detail);
        if ($product) {
            $product->setInStock($product->getInStock() - $detail->getQuantity());
            $this->entityManager->persist($product);
            $this->entityManager->flush($product);
        }
    }

    public function updateProductDetail(OrderDetail $detail, ?string $oldProductNumber = null, ?int $oldQuantity = null, ?string $newProductNumber = null, ?int $newQuantity = null): void
    {
        $oldQuantity = $oldQuantity === 0 || $oldQuantity > 0 ? $oldQuantity : $detail->getQuantity();
        $newQuantity = $newQuantity === 0 || $newQuantity > 0 ? $newQuantity : $detail->getQuantity();

        // If the position product has been changed, the old product stock must be increased based on the (old) ordering quantity.         // The stock of the new product will be reduced by the (new) ordered quantity.
$backup = new BackupModel();

        $backup->setFilterString($filterString);
        $backup->setOperationString($this->operationsToString($operations));
        $backup->setItems($items);
        $backup->setPath($path);
        $backup->setHash(sha1_file($path));
        $backup->setSize((int) filesize($path));

        $backup->setDate(new DateTime());

        $this->getDqlHelper()->getEntityManager()->persist($backup);
        $this->getDqlHelper()->getEntityManager()->flush($backup);
    }

    /** * Dumps a given table to disc - as only needed columns are exported, this is quite fast * * @param string $table * @param string $name * @param int[] $ids * @param bool $newBackup * * @throws RuntimeException */
if (!$product) {
            throw new NotFoundException(sprintf('Product by id %d not found', $productId));
        }

        $variant = $this->internalCreate($params$product);

        $violations = $this->getManager()->validate($variant);
        if ($violations->count() > 0) {
            throw new ValidationException($violations);
        }

        $this->getManager()->persist($variant);
        $this->flush();

        return $variant;
    }

    /** * Update function for the internal usage of the rest api. * Used from the 'Article' resource. This function supports * to pass an updated product entity which isn't updated in the database. * Required for the 'Article' resource if the product data is already updated * in the entity but not in the database. * * @param int $id * * @throws NotFoundException * @throws ParameterMissingException * * @return Detail */
if (!$code instanceof Code) {
            $this->View()->assign(['success' => false]);

            return;
        }

        $code->setCashed($this->Request()->getParam('cashed'));
        $code->setCode($this->Request()->getParam('code'));
        $code->setCustomerId($this->Request()->getParam('customerId'));

        $this->get(ModelManager::class)->persist($code);
        $this->get(ModelManager::class)->flush($code);

        $this->View()->assign(['success' => true]);
    }

    /** * exports all voucher codes via csv * * @return void */
    public function exportVoucherCodeAction()
    {
unset($params['action']);
            unset($params['_dc']);

            // 2-dimensional array             if (!empty($params[0])) {
                $data = [];
                foreach ($params as $values) {
                    $ruleModel = $this->get('models')->find(RuleSet::class$values['id']);

                    $ruleModel->fromArray($values);

                    $this->get('models')->persist($ruleModel);
                    $this->get('models')->flush();
                    $data[] = $this->get('models')->toArray($ruleModel);
                }
                $this->View()->assign(['success' => true, 'data' => $data]);
            } else {
                $ruleModel = $this->get('models')->find(RuleSet::class$params['id']);

                $ruleModel->fromArray($params);

                $this->get('models')->persist($ruleModel);
                $this->get('models')->flush();

                
Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $customerId,
            ]
        );

        $this->getContainer()->get(CartRuleLoader::class)->loadByToken($context$context->getToken());

        $cart = $this->processor->process($cart$contextnew CartBehavior());

        $id = $this->orderPersister->persist($cart$context);

        $count = $this->getContainer()->get(Connection::class)->fetchAllAssociative('SELECT * FROM `order` WHERE id = :id', ['id' => Uuid::fromHexToBytes($id)]);
        static::assertCount(1, $count);

        $this->orderRepository->delete([
            ['id' => $id],
        ], Context::createDefaultContext());

        $count = $this->getContainer()->get(Connection::class)->fetchAllAssociative('SELECT * FROM `order` WHERE id = :id', ['id' => Uuid::fromHexToBytes($id)]);
        static::assertCount(0, $count);
    }

    
// Set new image and extension if necessary         if (!empty($mediaManagerData)) {
            $bannerModel->setImage($mediaManagerData);
        }

        // Strip full qualified url         $mediaService = $this->get(MediaServiceInterface::class);
        $bannerModel->setImage($mediaService->normalize($bannerModel->getImage()));

        // Write model to db         try {
            $this->get('models')->persist($bannerModel);
            $this->get('models')->flush();
            $params['id'] = $bannerModel->getId();
            $this->View()->assign(['success' => 'true', 'data' => $params]);
        } catch (Exception $e) {
            $errorMsg = $e->getMessage();
            $this->View()->assign(['success' => 'false', 'errorMsg' => $errorMsg]);
        }
    }

    /** * Method to delete a banner. It takes either a single ID or an array of IDs to determine the banners to delete. * If there is no ID parameter given, it will look if there is a parameter banners available * * e.g. id=1 or banners[[id => 1], [id => 2], [id => 3]] */
$this->removeAlbumThumbnails($thumbnailSizes$this->getFileName());
    }

    /** * Internal helper function which updates all associated data which has the image path as own property. */
    private function updateAssociations()
    {
        /** @var Image $article */
        foreach ($this->articles as $article) {
            $article->setPath($this->getName());
            Shopware()->Models()->persist($article);
        }
        Shopware()->Models()->flush();
    }

    /**************************************************************** * Internal functions * ****************************************************************/

    /** * Moves the uploaded file to the correctly directory. * * @return bool */


        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }

        $ids = range(1, 300);

        foreach ($ids as $id) {
            $name = 65 + (int) \chr($id % 57);
            $this->em->persist(new SingleIntIdEntity($id$name));
        }

        $this->em->flush();
    }

    /** * This test case is realistic in collection forms where each * row contains the same entity field. * * @group benchmark */
    
$resource->setName($resourceName);
        $resource->setPluginId($pluginID);

        if (!empty($privileges)) {
            $privilegeObjects = [];

            foreach ($privileges as $name) {
                $privilege = new Privilege();
                $privilege->setName($name);
                $privilege->setResource($resource);

                $this->em->persist($privilege);

                $privilegeObjects[] = $privilege;
            }

            $resource->setPrivileges(new ArrayCollection($privilegeObjects));
        }

        $this->em->persist($resource);
        $this->em->flush();
    }

    
protected function resolveCacheMiss($key) {
    $ids = $this->entityTypeManager->getStorage('block_content')->getQuery()
      ->accessCheck(FALSE)
      ->condition('uuid', $key)
      ->execute();

    // Only cache if there is a match, otherwise creating new entities would     // require to invalidate the cache.     $id = reset($ids);
    if ($id) {
      $this->storage[$key] = $id;
      $this->persist($key);
    }
    return $id;
  }

}

    public function createFormAction()
    {
        $params = $this->Request()->getParams();

        $formModel = new Form();
        $params['shopIds'] = $params['shopIds'] ? '|' . implode('|', $params['shopIds']) . '|' : null;

        $formModel->fromArray($params);

        $this->getManager()->persist($formModel);
        $this->getManager()->flush();

        $data = $this->getManager()->toArray($formModel);
        $data['shopIds'] = $this->explodeShopIds($data['shopIds']);

        $this->View()->assign(['success' => true, 'data' => $data]);
    }

    /** * Updates form * * @throws OptimisticLockException * @throws ORMInvalidArgumentException */
$data = $this->implodePriceVariation($data);

            $priceVariation->fromArray($data);
            $modelManager = $this->get(\Shopware\Components\Model\ModelManager::class);
            /** @var Set|null $configuratorSet */
            $configuratorSet = $modelManager
                    ->getRepository(Set::class)
                    ->find($data['configuratorSetId']);
            $priceVariation->setConfiguratorSet($configuratorSet);

            $modelManager->persist($priceVariation);
            $modelManager->flush();

            $data['id'] = $priceVariation->getId();
            $data = $this->explodePriceVariation($data);

            $this->View()->assign([
                'success' => true,
                'data' => $data,
            ]);
        } catch (Exception $e) {
            $this->View()->assign([
                
Home | Imprint | This part of the site doesn't use cookies.