Magento – How to save values in Custom Entity table – Magento 2

eavmagento2

I have created a module in Magento 2 which has EAV structured tables.

Created the tables and attributes by Install Schema. But I am not able to save values in to these tables.

My tables are

  1. custom_entity

entity_id | attribute_set_id | type_id | customer_id |created_at | updated_at

  1. ustom_entity_varchar

entity_id | attribute_id | store_id | value_id | value

Can any one please provide me the code to save the values to the tables specified above?

Best Answer

There many links available for CRUD magento 2, below link is explain excellent. You can refer this link. I assuming, you have created Model.
Below controller code will save values in table.

namespace ext\cust_module\Controller\Save;
use Magento\Framework\Controller\ResultFactory;
class Save extends \Magento\Framework\App\Action\Action
{
    protected $CustomEntityFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \<ext>\CustomEntity\Model\CustomEntityFactory $CustomEntityFactory,

    )
    {
        $this->CustomEntityFactory = $CustomEntityFactory;
        parent::__construct($context);
    }

    public function execute() 
    {   
        //entity_id  | attribute_set_id  | type_id  | customer_id  |created_at  | updated_at 
        // Your value in variable  
        $attribute_set_id = '';
        $msg = '';
        $CF = $this->CustomEntityFactory->create();
                $CF->setData(array('attribute_set_id' => $attribute_set_id, 'type_id' => $type_id)) 
                    ->save();
        $msg = 'Your value has been updated';       
        $this->messageManager->addSuccess(
                        __($msg)
                );
        return $resultRedirect->setPath('<ext>_CustomEntity/', ['_current' => true]); 
    }   

}
Related Topic