So instead of update the student, this code add a new student.
I'm looking for a way that not using object manager, because the objectmanager is recommended not to use.
So when i searching for how to update a product in magento 2
, i found alot of objectmanager
way, but like i said, i wont use them.
I found 2 other ways, 1st way is using factory
only, the 2nd way is using resource model
and factory
.
So here is the code :
namespace Fudu\HelloWorld\Controller\Adminhtml\Student;
use Magento\Backend\App\Action\Context;
use Fudu\HelloWorld\Model\StudentsFactory;
use Fudu\HelloWorld\Model\ResourceModel\Students as ResourceModel;
class Update extends \Magento\Framework\App\Action\Action
{
/**
* @var StudentsFactory
*/
protected $studentsFactory;
/**
* @var ResourceModel
*/
protected $resourceModel;
public function __construct(
Context $context,
StudentsFactory $studentsFactory,
ResourceModel $resourceModel
) {
$this->resourceModel = $resourceModel;
$this->studentsFactory = $studentsFactory;
parent::__construct($context);
}
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$data = $this->getRequest()->getPostValue();
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//
if ($data) {
try{
/** @var \Fudu\HelloWorld\Model\Students $model */
$id = $this->getRequest()->getParam('id');
// The 1st way :
$model = $this->studentsFactory->create()->load($id);
$model->setData($data);
$model->save();
// The 2nd way :
// $model = $this->studentsFactory->create();
// $resource = $this->resourceModel->load($model,$id);
// $model->setData($data);
// $resource->save($model);
$this->messageManager->addSuccessMessage(__('Update Student Successfully.'));
// Redirect to your form page (or anywhere you want...)
$resultRedirect->setPath('students/student/index');
return $resultRedirect;
}
catch (\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
}
}
}