1

Before all I am using Magento 2.1.2, with a custom entity.

I am trying to save multiple row in a flat table that I have created with $connection->insertMultiple($this->getMainTable(), $answers);

For that I am using the following code to populate missing row lines

$dataUserAnswer = $this->dataUserAnswerFactory->create();

$this->dataObjectHelper->populateWithArray(
    $dataUserAnswer,
    $answers,
    'XXX\YYY\Api\Data\UserAnswerInterface'
);
$userAnswers[] = $this->dataObjectProcessor->buildOutputDataArray(
    $dataUserAnswer,
    'XXX\YYY\Api\Data\UserAnswerInterface'
);

With the classes Magento\Framework\Api\DataObjectHelper and Magento\Framework\Reflection\DataObjectProcessor

Here is the result I get

[0] => array(7) {
    ["id"] => NULL
    ["poll_question_id"] => int(1)
    ["poll_answer_id"] => string(1) "1"
    ["value"] => string(0) ""
    ["customer_id"] => string(1) "1"
    ["created_at"] => NULL
    ["updated_at"] => NULL
}

Which is nearly what I want except for the id entry. In my Api/Data/Interface I declare a constant const ID = 'id'; with getter and setter getId() / setId($id).
I took a look at Customer module to have an exemple to build my entity.
Magento best practice is to have the primary key as entity_id.

I understand that buildOutputDataArray use Reflexion class to retrive getter and then deduce entity fields to fill missing fields.

My questions are :
- What is the best pratice for API interface constante / setter / getter ? id ? entity_id ?
- If I am taking a look at Customerentity, primary key is entity_id but constante is id. Do I miss something ? Am I doing this the wrong way ?

Hope my problem is clear.
Thank you !

1 Answer 1

2

I will answer my own question for people seeing this post.

I had to create setEntityId / getEntityId in my API interface and remove the getId / setId because it already exist in the parent class \Magento\Framework\Model\AbstractModel::getId so it does not matter if it is not present in the API interface.
And add the following code in my model as for Magento 1:

/**
 * Name of object id field
 *
 * @var string
 */
protected $_idFieldName = 'entity_id';  

I had take a look at the wrong entity for my exemple...

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.