2

I'm trying to insert a row in a table using following code inside controller.

protected $_objectManager;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\ObjectManagerInterface $objectManager
) 
{
    $this->_objectManager = $objectManager;
    parent::__construct($context);    
}

public function execute()
{
    $post = $this->getRequest()->getParams();
    $model = $this->_objectManager->create('<<Company Name>>\<<Module Name>>\Model\XYZ');
    $model->setData('name', $post["name"]);
    $model->setData('customer_id', $post["customer_id"]);
    $model->setData('customer_is_guest', $post["customer_is_guest"]);
    $model->setData('testCol', $post["test_col"]);

    $model->save();
}

Above code works and row gets inserted into the table, is there a way to get the id (identity id) of the row inserted above?

1 Answer 1

5
$model->getId();

if you plan to use it right after you call save.

Side note...please don't use object manager directly in your code.
Make your class look like this :

protected $modelFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \<<Company Name>>\<<Module Name>>\Model\XYZFactory $modelFactory
) 
{
    $this->modelFactory = $modelFactory;
    parent::__construct($context);    
}

public function execute()
{
    $post = $this->getRequest()->getParams();
    $model = $this->modelFactory->create();
    $model->setData('name', $post["name"]);
    $model->setData('customer_id', $post["customer_id"]);
    $model->setData('customer_is_guest', $post["customer_is_guest"]);
    $model->setData('testCol', $post["test_col"]);

    $model->save();
}
2
  • $model->save() is depricated. It's recommended to save with the repository->save($model) or resource_model->save($model). But resource model returns itself in save method. So how could I get the primary key in this case? Mar 4, 2019 at 12:23
  • 2
    in a similar way you will call $repository->save($model) and then get $model->getId()
    – Marius
    Mar 4, 2019 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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