0

I'm trying to update a field in the database via my database model. All tutorials online about CRUD models seem to just show how to 'CR' and not showing examples of the 'UD'. My code so far:

namespace CompanyName\AdminMenu\Controller\Adminhtml\HomepageBanner;

class UpdatePosition extends \Magento\Framework\App\Action\Action
{
protected $_postFactory;
protected $_httpRequest;
protected $_postResource;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\App\Request\Http $httpRequest,
    \CompanyName\AdminMenu\Model\PostFactory $postFactory,
    \CompanyName\AdminMenu\ResourceModel\Post $postResource
    )
{
    $this->_postFactory = $postFactory;
    $this->_postResource = $postResource;
    $this->_httpRequest = $httpRequest;
    return parent::__construct($context);
}

public function execute()
{
    $post = $this->$postFactory->create();

    $post->load(2, 'slide_position')->setId(22)->save();

    //$this->getConnection()->update('admincontentbanners_homepageslider_post', ['slide_position' => $data], ["slide_id = ?" => $slideID]);
}

}

Any advise would be appreciated..

  • Use repository instead of model and cms module is good example of CRUD. – Sohel Rana Jun 3 '18 at 18:38
  • I didn't know about repositories.. Ill look into using those now.. Man, Magneto moves fast! – Bossman Jun 3 '18 at 19:06
0

This loads the specified model , which you want update .

public function execute()
    {
        $post = $this->$postFactory->create();
        $id_post_update = 19; //Example

        $postUpdate = $post->load($id_post_update);
        $postUpdate->setSlidePosition(2);
        $postUpdate->setId(22);
        $postUpdate->save();
    }
  • I'm going to look into repositories now but is "$id_post_update" the primary table ID field? "setSlidePosition()" is that a generated function? – Bossman Jun 3 '18 at 19:08
  • $id_post_update - this id entity post, which you want update ;"setSlidePosition()" - this magic method , which update 'slide_position' – Evgeniy Kapelko Jun 3 '18 at 19:17
  • Thanks for your help, i managed to get it working with your code, i didn't need the "$postUpdate->setId(22);" – Bossman Jun 4 '18 at 20:02
  • Sorry , I get this "->setId(22)" from your example . – Evgeniy Kapelko Jun 4 '18 at 20:13
  • Yes, that was just me not understanding fully :) – Bossman Jun 4 '18 at 21:17
0

Evgeniy Kapelko approach works, but deprecated from Magento 2.1(with certain version I might be mistaken).
Below infromation from class, that was used in Evgeniy Kapelko approach, confirm info about deprecation vendor/magento/framework/Model/AbstractModel.php

/**
 * Save object data
 *
 * @return $this
 * @throws \Exception
 *
 * @deprecated 100.1.0 because entities must not be responsible for their own persistence.
 * Service contracts should persist entities. Use resource model "save" to implement
 * service contract persistence operations.
 */
public function save()
{
    $this->_getResource()->save($this);
    return $this;
}


How correct to work with you model?
We need to use it like described in official documentation.

It can be little bit hard at the begging, but future code will be simple and clear.

In code below, we are going to update Shop entity name.
1) Create interface for you repository, with functions getById and save

<?php

namespace Vendor\Module\Api;

use Vendor\Module\Api\Data\ShopInterface;

/**
 * Interface SampleInterface
 *
 * @package Academy\Database\Api\Data
 */
interface ShopRepositoryInterface
{

    /**
     * @param \Vendor\Module\Api\Data\ShopInterface $shopList
     *
     * @return mixed
     */
    public function save(ShopInterface $shopList);

    /**
     * @param int $id
     *
     * @return mixed
     */
    public function getById(int $id);
}

2) Implement interface in you repository and define functions

<?php

namespace Vendor\Module\Model;


use Vendor\Module\Api\Data\ShopInterface;
use Vendor\Module\Api\ShopRepositoryInterface;
use Vendor\Module\Model\ResourceModel\Shop as ShopResource;
use Magento\Framework\Exception\AlreadyExistsException;

class ShopRepository implements ShopRepositoryInterface
{

    /**
     * @var ShopFactory
     */
    private $shopList;
    /**
     * @var Shop
     */
    private $shopListResource;

    public function __construct(
        ShopFactory $shopList,
        ShopResource $shopListResource
    ) {
        $this->shopList         = $shopList;
        $this->shopListResource = $shopListResource;
    }

    /**
     * @param ShopInterface $shop
     *
     * @return void
     *
     * @throws AlreadyExistsException
     * @throws \Exception
     */
    public function save(ShopInterface $shop)
    {
        try {
            $this->shopListResource->save($shop);
        } catch (AlreadyExistsException $e) {
            //catch exception
        } catch (\Exception $e) {
            //catch exception
        }
    }

    /**
     * @param int $shopId
     *
     * @return \Vendor\Module\Model\Shop
     */
    public function getById(int $shopId)
    {
        $shopListModel = $this->shopList->create();
        $this->shopListResource->load($shopListModel, $shopId);

        return $shopListModel;
    }
}

3) Add Repository and RepositoryInterface to di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Vendor\Module\Api\ShopRepositoryInterface"
                type="Vendor\Module\Model\ShopRepository"/>
</config>

4) Start using it (i'm using it in controller)

    /**
     * @param ShopInterfaceFactory    $shopListFactory
     * @param ShopRepositoryInterface $shopListRepository
     */
    public function __construct(
        \Vendor\Module\Api\Data\ShopInterfaceFactory $shopListFactory,
        \Vendor\Module\Api\ShopRepositoryInterface $shopListRepository
    ) {
        $this->shopListFactory    = $shopListFactory;
        $this->shopListRepository = $shopListRepository;
    }

    public function execute()
    {
        $shopId = 1;//use needed entity ID

        /**
         * Create entity
         *
         * @var Shop $shopList
         */
        $shopList = $this->shopListFactory->create();
        $shopList->setData(['name' => 'shop name']);
        $this->shopListRepository->save($shopList);

        /**
         * Read entity
         *
         * @var Shop $shopList
         */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopData = $shopList->getData();//data of entity

        /**
         * Update entity
         *
         * @var Shop $shopList
         */
        $shopList = $this->shopListRepository->getById($shopId);
        $shopList->addData(['name' => 'bdn']);
        $this->shopListRepository->save($shopList);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.