Search code examples
formsentityshopwarestorefront

Shopware 6 Forms


Newbie question. How to handle Storefront Form Submit in Shopware 6? How to save the data from form to database? I have an entity, form shown in storefront and a controller but i have no idea how to save the data to entity. Thanks in advance.


Solution

  • you would have to be more specific with the description, of what exactly you are trying to achieve.

    But in general, if you already have a controller, that receives the data, then you can get them from the request like this:

    $data = $request->request->all();
    

    By this, you have all the values from your form saved in an array $data. You have written, that you already have an entity, so from that I assume, that your entity is already mapped to your database table. So the only thing you have to do, is to use the repository to save the data. For thta, you just need to inject it into your class and get a context. The context depends on where you currently are, so for the purpose of the example, I have just created the default context.

    It should look like this:

    class MyClass
    {
    
        protected $myEntityRepository;
    
        public function __construct(
            MyEntityRepository $myEntityRepository
        )
        {
            $this->myEntityRepository = $myEntityRepository;
    
            $this->context = \Shopware\Core\Framework\Context::createDefaultContext();
        }
    
        public function myMethod ($data)
        {
    
            $this->myEntityRepository->upsert($data, $this->context);
    
        }
    
    }
    

    Hope this helps. I have actually written an article on repositories in Shopware 6, so if you want to get some more information and examples, you can check it here: https://shopwarian.com/repositories-in-shopware-6/.