I have created a new table in Magento2: my_custom_table with 4 fields:

id: primary key, 
product_id: int(11), 
customer_id: int(11)

I want to save multiple records at a time. Here is my code.

namespace Company\Module\Controller\Adminhtml\Index;    

class Save extends \Company\Module\Controller\Adminhtml\Index

        protected $_filterProvider;
        protected $productModel;

        public function __construct(
            \Magento\Backend\App\Action\Context $context,
            \Magento\Framework\Registry $registry,
            \Magento\Cms\Model\Template\FilterProvider $filterProvider,
            \Company\Module\Model\Product  $productModel

        ) {
            $this->_filterProvider = $filterProvider;
            $this->productModel = $productModel;      


        public function execute()
            $resultRedirect = $this->resultRedirectFactory->create();
            $data = $this->getRequest()->getPostValue();
            if ($data) {
                $products = array(12,13,14,14);
                $customerId = 1;
                foreach($products as $pdt){
                    $productModel = $this->productModel;                                  
            return $resultRedirect->setPath('*/*/new');


Please help me

  • As far as i know only u can do with for loop.
    – Jackson
    Dec 28, 2016 at 6:10
  • But it adds only one row Dec 28, 2016 at 6:11
  • Follow this magento.stackexchange.com/questions/140612/…
    – Jackson
    Dec 28, 2016 at 6:15
  • Please share your modules, complete code, also make sure your primary key should be auto increment.
    – Arunendra
    Dec 28, 2016 at 6:23
  • yes. primary key is auto increment. Please check the updated code Dec 28, 2016 at 6:47

1 Answer 1


We forgot to unset data model after saving.



Using model Factory can solve our issue. For example, inject Company\Module\Model\ProductFactory in constructor . Inside the loop, we just need to create the factory.

$product = $this->productFactory->create();

Your Answer

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

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