Magento 2.2.5: Add Student Instead of Update Student












3















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 FuduHelloWorldControllerAdminhtmlStudent;

use MagentoBackendAppActionContext;
use FuduHelloWorldModelStudentsFactory;
use FuduHelloWorldModelResourceModelStudents as ResourceModel;

class Update extends MagentoFrameworkAppActionAction
{
/**
* @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 MagentoFrameworkControllerResultInterface
*/
public function execute()
{
$data = $this->getRequest()->getPostValue();

/** @var MagentoBackendModelViewResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//
if ($data) {
try{
/** @var FuduHelloWorldModelStudents $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());
}

}
}
}


Thanks for reading, and have a good day










share|improve this question





























    3















    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 FuduHelloWorldControllerAdminhtmlStudent;

    use MagentoBackendAppActionContext;
    use FuduHelloWorldModelStudentsFactory;
    use FuduHelloWorldModelResourceModelStudents as ResourceModel;

    class Update extends MagentoFrameworkAppActionAction
    {
    /**
    * @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 MagentoFrameworkControllerResultInterface
    */
    public function execute()
    {
    $data = $this->getRequest()->getPostValue();

    /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    //
    if ($data) {
    try{
    /** @var FuduHelloWorldModelStudents $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());
    }

    }
    }
    }


    Thanks for reading, and have a good day










    share|improve this question



























      3












      3








      3








      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 FuduHelloWorldControllerAdminhtmlStudent;

      use MagentoBackendAppActionContext;
      use FuduHelloWorldModelStudentsFactory;
      use FuduHelloWorldModelResourceModelStudents as ResourceModel;

      class Update extends MagentoFrameworkAppActionAction
      {
      /**
      * @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 MagentoFrameworkControllerResultInterface
      */
      public function execute()
      {
      $data = $this->getRequest()->getPostValue();

      /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
      $resultRedirect = $this->resultRedirectFactory->create();
      //
      if ($data) {
      try{
      /** @var FuduHelloWorldModelStudents $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());
      }

      }
      }
      }


      Thanks for reading, and have a good day










      share|improve this question
















      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 FuduHelloWorldControllerAdminhtmlStudent;

      use MagentoBackendAppActionContext;
      use FuduHelloWorldModelStudentsFactory;
      use FuduHelloWorldModelResourceModelStudents as ResourceModel;

      class Update extends MagentoFrameworkAppActionAction
      {
      /**
      * @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 MagentoFrameworkControllerResultInterface
      */
      public function execute()
      {
      $data = $this->getRequest()->getPostValue();

      /** @var MagentoBackendModelViewResultRedirect $resultRedirect */
      $resultRedirect = $this->resultRedirectFactory->create();
      //
      if ($data) {
      try{
      /** @var FuduHelloWorldModelStudents $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());
      }

      }
      }
      }


      Thanks for reading, and have a good day







      magento2.2 resource-model object-manager factory crud






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 26 mins ago









      Teja Bhagavan Kollepara

      2,94841847




      2,94841847










      asked Jul 21 '18 at 3:41









      fudufudu

      38411




      38411






















          2 Answers
          2






          active

          oldest

          votes


















          3














          $model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code:




          $id = $this->getRequest()->getParam('id');
          $model = $this->studentsFactory->create()->load($id);
          if ($model->getId()) {
          $model->setData($data);
          $model->setId($id);
          } else {
          $model->setData($data);
          }

          $model->save();





          share|improve this answer
























          • yes thanks you, +1 vote for you my friend

            – fudu
            Jul 21 '18 at 4:49



















          2














          Try to use this below code :



          namespace FuduHelloWorldControllerAdminhtmlStudent;

          use MagentoBackendAppActionContext;
          use FuduHelloWorldModelStudentsFactory;

          class Update extends MagentoFrameworkAppActionAction
          {
          /**
          * @var StudentsFactory
          */
          protected $studentsFactory;


          public function __construct(
          Context $context,
          StudentsFactory $studentsFactory
          ) {
          $this->studentsFactory = $studentsFactory;
          parent::__construct($context);
          }

          public function execute()
          {
          $data = $this->getRequest()->getPostValue();

          /** @var MagentoBackendModelViewResultRedirect $resultRedirect */

          if ($data) {
          try {
          $model = $this->studentsFactory->create();
          $model->setData($data);
          $model->save();

          $this->messageManager->addSuccessMessage(__('Add data Successfully.'));
          $resultRedirect->setPath('students/student/index');
          return $resultRedirect;
          }
          catch (Exception $e) {
          $this->messageManager->addErrorMessage($e->getMessage());
          }

          }
          }
          }


          Remove generation and check it.






          share|improve this answer
























          • doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

            – fudu
            Jul 21 '18 at 4:48













          • I thought Your question title is about add record. So, I upload that answer.

            – Rohan Hapani
            Jul 21 '18 at 5:17











          • LOL :D sorry because confusing you.

            – fudu
            Jul 21 '18 at 5:25











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "479"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f235374%2fmagento-2-2-5-add-student-instead-of-update-student%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          $model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code:




          $id = $this->getRequest()->getParam('id');
          $model = $this->studentsFactory->create()->load($id);
          if ($model->getId()) {
          $model->setData($data);
          $model->setId($id);
          } else {
          $model->setData($data);
          }

          $model->save();





          share|improve this answer
























          • yes thanks you, +1 vote for you my friend

            – fudu
            Jul 21 '18 at 4:49
















          3














          $model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code:




          $id = $this->getRequest()->getParam('id');
          $model = $this->studentsFactory->create()->load($id);
          if ($model->getId()) {
          $model->setData($data);
          $model->setId($id);
          } else {
          $model->setData($data);
          }

          $model->save();





          share|improve this answer
























          • yes thanks you, +1 vote for you my friend

            – fudu
            Jul 21 '18 at 4:49














          3












          3








          3







          $model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code:




          $id = $this->getRequest()->getParam('id');
          $model = $this->studentsFactory->create()->load($id);
          if ($model->getId()) {
          $model->setData($data);
          $model->setId($id);
          } else {
          $model->setData($data);
          }

          $model->save();





          share|improve this answer













          $model->setData($data); this line reset your data. If there id field present $data variable then your code working fine. Otherwise you need to set id for update. Check following code:




          $id = $this->getRequest()->getParam('id');
          $model = $this->studentsFactory->create()->load($id);
          if ($model->getId()) {
          $model->setData($data);
          $model->setId($id);
          } else {
          $model->setData($data);
          }

          $model->save();






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jul 21 '18 at 4:43









          Sohel RanaSohel Rana

          21.2k34458




          21.2k34458













          • yes thanks you, +1 vote for you my friend

            – fudu
            Jul 21 '18 at 4:49



















          • yes thanks you, +1 vote for you my friend

            – fudu
            Jul 21 '18 at 4:49

















          yes thanks you, +1 vote for you my friend

          – fudu
          Jul 21 '18 at 4:49





          yes thanks you, +1 vote for you my friend

          – fudu
          Jul 21 '18 at 4:49













          2














          Try to use this below code :



          namespace FuduHelloWorldControllerAdminhtmlStudent;

          use MagentoBackendAppActionContext;
          use FuduHelloWorldModelStudentsFactory;

          class Update extends MagentoFrameworkAppActionAction
          {
          /**
          * @var StudentsFactory
          */
          protected $studentsFactory;


          public function __construct(
          Context $context,
          StudentsFactory $studentsFactory
          ) {
          $this->studentsFactory = $studentsFactory;
          parent::__construct($context);
          }

          public function execute()
          {
          $data = $this->getRequest()->getPostValue();

          /** @var MagentoBackendModelViewResultRedirect $resultRedirect */

          if ($data) {
          try {
          $model = $this->studentsFactory->create();
          $model->setData($data);
          $model->save();

          $this->messageManager->addSuccessMessage(__('Add data Successfully.'));
          $resultRedirect->setPath('students/student/index');
          return $resultRedirect;
          }
          catch (Exception $e) {
          $this->messageManager->addErrorMessage($e->getMessage());
          }

          }
          }
          }


          Remove generation and check it.






          share|improve this answer
























          • doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

            – fudu
            Jul 21 '18 at 4:48













          • I thought Your question title is about add record. So, I upload that answer.

            – Rohan Hapani
            Jul 21 '18 at 5:17











          • LOL :D sorry because confusing you.

            – fudu
            Jul 21 '18 at 5:25
















          2














          Try to use this below code :



          namespace FuduHelloWorldControllerAdminhtmlStudent;

          use MagentoBackendAppActionContext;
          use FuduHelloWorldModelStudentsFactory;

          class Update extends MagentoFrameworkAppActionAction
          {
          /**
          * @var StudentsFactory
          */
          protected $studentsFactory;


          public function __construct(
          Context $context,
          StudentsFactory $studentsFactory
          ) {
          $this->studentsFactory = $studentsFactory;
          parent::__construct($context);
          }

          public function execute()
          {
          $data = $this->getRequest()->getPostValue();

          /** @var MagentoBackendModelViewResultRedirect $resultRedirect */

          if ($data) {
          try {
          $model = $this->studentsFactory->create();
          $model->setData($data);
          $model->save();

          $this->messageManager->addSuccessMessage(__('Add data Successfully.'));
          $resultRedirect->setPath('students/student/index');
          return $resultRedirect;
          }
          catch (Exception $e) {
          $this->messageManager->addErrorMessage($e->getMessage());
          }

          }
          }
          }


          Remove generation and check it.






          share|improve this answer
























          • doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

            – fudu
            Jul 21 '18 at 4:48













          • I thought Your question title is about add record. So, I upload that answer.

            – Rohan Hapani
            Jul 21 '18 at 5:17











          • LOL :D sorry because confusing you.

            – fudu
            Jul 21 '18 at 5:25














          2












          2








          2







          Try to use this below code :



          namespace FuduHelloWorldControllerAdminhtmlStudent;

          use MagentoBackendAppActionContext;
          use FuduHelloWorldModelStudentsFactory;

          class Update extends MagentoFrameworkAppActionAction
          {
          /**
          * @var StudentsFactory
          */
          protected $studentsFactory;


          public function __construct(
          Context $context,
          StudentsFactory $studentsFactory
          ) {
          $this->studentsFactory = $studentsFactory;
          parent::__construct($context);
          }

          public function execute()
          {
          $data = $this->getRequest()->getPostValue();

          /** @var MagentoBackendModelViewResultRedirect $resultRedirect */

          if ($data) {
          try {
          $model = $this->studentsFactory->create();
          $model->setData($data);
          $model->save();

          $this->messageManager->addSuccessMessage(__('Add data Successfully.'));
          $resultRedirect->setPath('students/student/index');
          return $resultRedirect;
          }
          catch (Exception $e) {
          $this->messageManager->addErrorMessage($e->getMessage());
          }

          }
          }
          }


          Remove generation and check it.






          share|improve this answer













          Try to use this below code :



          namespace FuduHelloWorldControllerAdminhtmlStudent;

          use MagentoBackendAppActionContext;
          use FuduHelloWorldModelStudentsFactory;

          class Update extends MagentoFrameworkAppActionAction
          {
          /**
          * @var StudentsFactory
          */
          protected $studentsFactory;


          public function __construct(
          Context $context,
          StudentsFactory $studentsFactory
          ) {
          $this->studentsFactory = $studentsFactory;
          parent::__construct($context);
          }

          public function execute()
          {
          $data = $this->getRequest()->getPostValue();

          /** @var MagentoBackendModelViewResultRedirect $resultRedirect */

          if ($data) {
          try {
          $model = $this->studentsFactory->create();
          $model->setData($data);
          $model->save();

          $this->messageManager->addSuccessMessage(__('Add data Successfully.'));
          $resultRedirect->setPath('students/student/index');
          return $resultRedirect;
          }
          catch (Exception $e) {
          $this->messageManager->addErrorMessage($e->getMessage());
          }

          }
          }
          }


          Remove generation and check it.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jul 21 '18 at 4:27









          Rohan HapaniRohan Hapani

          1




          1













          • doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

            – fudu
            Jul 21 '18 at 4:48













          • I thought Your question title is about add record. So, I upload that answer.

            – Rohan Hapani
            Jul 21 '18 at 5:17











          • LOL :D sorry because confusing you.

            – fudu
            Jul 21 '18 at 5:25



















          • doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

            – fudu
            Jul 21 '18 at 4:48













          • I thought Your question title is about add record. So, I upload that answer.

            – Rohan Hapani
            Jul 21 '18 at 5:17











          • LOL :D sorry because confusing you.

            – fudu
            Jul 21 '18 at 5:25

















          doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

          – fudu
          Jul 21 '18 at 4:48







          doesn't work though .. @@ the way of @Sohel Rana up there is work . But thanks you for help.

          – fudu
          Jul 21 '18 at 4:48















          I thought Your question title is about add record. So, I upload that answer.

          – Rohan Hapani
          Jul 21 '18 at 5:17





          I thought Your question title is about add record. So, I upload that answer.

          – Rohan Hapani
          Jul 21 '18 at 5:17













          LOL :D sorry because confusing you.

          – fudu
          Jul 21 '18 at 5:25





          LOL :D sorry because confusing you.

          – fudu
          Jul 21 '18 at 5:25


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f235374%2fmagento-2-2-5-add-student-instead-of-update-student%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          What other Star Trek series did the main TNG cast show up in?

          Berlina muro

          Berlina aerponto