1

I'm trying to save records using the controller. I set foreign key in attribute_set_id and entity_type_id field in main table with eav_attribute_set and eav_entity_type respectivelly.

But, when I save records it can't save.

Controller code :

<?php
namespace VendorName\ModuleName\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    /**
    * @var \Magento\Framework\View\Result\PageFactory
    */
    protected $resultPageFactory;
    protected $moduleNameFactory;
    protected $_dateFactory;
    /**
    * @param \Magento\Framework\App\Action\Context $context
    * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
    * @param \VendorName\ModuleName\Model\ModuleNameFactory $moduleNameFactory
    */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \VendorName\ModuleName\Model\ModuleNameFactory $moduleNameFactory,
        \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateFactory
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->moduleNameFactory = $moduleNameFactory;
        $this->_dateFactory = $dateFactory;
        parent::__construct($context);
    }
    /**
    * @return void
    */
    public function execute()
    {
        $module = $this->moduleNameFactory->create();
        $module->setEntityTypeId(15); // this value can't saved in main table
        $module->setAttributeSetId(22); // this value can't saved in main table
        $module->setTitle('Title');
        $module->setUrl('url');
        $module->setDesc('desc');
        $module->setStatus(1);
        $module->setCreatedAt($this->_dateFactory->create()->date());
        $module->setUpdatedAt($this->_dateFactory->create()->date());
        $module->save();
    }
}
?>

InstallSchema.php :(entity_type_id & attribute_set_id code)

$table->addColumn(
            'entity_type_id',
            Table::TYPE_SMALLINT,
            null,
            [
                'unsigned' => true,
                'nullable' => false,
                'default' => '0',
            ],
            'Entity Type ID'
        )->addIndex(
            $setup->getIdxName($tableName, ['entity_type_id']),
            ['entity_type_id']
        )->addForeignKey(
            $setup->getFkName(
                'vendorname_modulename_entity',
                'entity_type_id',
                'eav_entity_type',
                'entity_type_id'
            ),
            'entity_type_id',
            $setup->getTable('eav_entity_type'),
            'entity_type_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE,
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
        );

        $table->addColumn(
            'attribute_set_id',
            Table::TYPE_SMALLINT,
            null,
            [
                'unsigned' => true,
                'nullable' => false,
                'default' => '0',
            ],
            'Attribute Set ID'
        )->addIndex(
            $setup->getIdxName($tableName, ['attribute_set_id']),
            ['attribute_set_id']
        )->addForeignKey(
            $setup->getFkName(
                'vendorname_modulename_entity',
                'attribute_set_id',
                'eav_attribute_set',
                'attribute_set_id'
            ),
            'attribute_set_id',
            $setup->getTable('eav_attribute_set'),
            'attribute_set_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE,
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
        );

It returns error when save :

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (m226.vendorname_modulename_entity, CONSTRAINT FK_5F02A602AEE613FE515E787AA9C5EB1F FOREIGN KEY (entity_type_id) REFERENCES eav_entity_type (entity_type_id) ON DELETE CASCADE), query was: INSERT INTO vendorname_modulename_entity (created_at, updated_at) VALUES ('2019-03-01 06:04:57', '2019-03-01 06:04:57')"

If, I set default value null in both field then, error not return but field always set null value.

How to solve it?

Any help would be appriciated.

2

As we can see in the error message, the insert is not correct as there are only two columns in the statement and that is obvious wrong: INSERT INTO vendorname_modulename_entity (created_at, updated_at) VALUES ('2019-03-01 06:04:57', '2019-03-01 06:04:57').

The problem might be in your model or resource model: Did you define a method setEntityTypeId in your model which sets the entity tyo or type id in resource model? If not your method can't do what you expect. The easiest way imho is to set the entity type directly in your resource model since it is fixed. In this way you don't need to set it for every entity.

Add a function like this in your resource model:

public function getEntityType() {
    if(empty($this->_type)) {
        $this->setType('your_entity_type_code_here');
    }

    return parent::getEntityType();
}

After debugging the code together in the chat, the solution was to build the resource model only with the above method and _getDefaultAttributes() like follows:

protected function _getDefaultAttributes()
{
    return ['entity_type_id', 'attribute_set_id', 'created_at', 'updated_at'];
}
  • Did you define a method setEntityTypeId in your model which sets the entity tyo or type id in resource model? : No, Can you please add code here? I added getEntityType() function in resourceModel. – Emipro Technologies Pvt. Ltd. Mar 1 at 8:46
  • If you have added getEntityType() function in resourceModel and try to save the model whithout calling $model->setEntityTypeId what happens? Same error? – HelgeB Mar 1 at 8:49
  • Yes. still same. I just temporary change type of entity_type_id default is null. So, It's save NULL instead of entity_type_id. – Emipro Technologies Pvt. Ltd. Mar 1 at 8:53
  • In the AbstractEntity the value of entity_typ_id is taken from your getEntityType method like this: $this->getEntityType()->getEntityTypeId() so usually there is no need to set it. I guess there is something else wrong with your eav entity model or resource model. I would try to debug somewhere in a method like _beforeSave(). Do you have a stacktrace from your exception? – HelgeB Mar 1 at 9:01
  • Where should add this method _beforeSave()? – Emipro Technologies Pvt. Ltd. Mar 1 at 9:03

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.