I want to add created_at and updated_at columns in a custom table and update both columns on saving the data.
1 Answer
Follow below steps to update the created_at and update_at columns on saving the data in the table.
- Create created_at and update_at columns in the database table.
.................
<column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Creation Time"/>
<column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Update Time"/>
.................
- Update the Model/CustomTable.php file to add
beforeSave()
function.
use Magento\Framework\Api\DataObjectHelper;
class CustomTable extends \Magento\Framework\Model\AbstractModel
{
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
private $dateTime;
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Stdlib\DateTime $dateTime,
DataObjectHelper $dataObjectHelper,
array $data = []
) {
$this->dateTime = $dateTime;
$this->dataObjectHelper = $dataObjectHelper;
parent::__construct(....);
}
/**
* Prepare data to be saved to database.
*
* @return $this
*/
public function beforeSave()
{
parent::beforeSave();
if ($this->isObjectNew() && !$this->getCreatedAt()) {
$this->setCreatedAt($this->dateTime->formatDate(true));
}
$this->setUpdatedAt($this->dateTime->formatDate(true));
return $this;
}
}
Hope this works for you.