1

I have created a custom module and I have a custom phtml file with a form.

I have also created a new table for this module.

What I want to do is to insert the value of form in the DB But I actually don't know the flow for that.

What I mean is how can I send my form to a controller and then access the model to make operations?

Can anyone help my with an example how to do that?

Thank you in advance!

2 Answers 2

1

You need to create controller first and add it on form action.

Then in controller you can get form values by :

$name = $this->getRequest()->getPostValue("name"); // here i have taken example for name field

Then same way you need to create model and resource model to store data in your custom table.

Refer this link for more details - http://clever-code.com/how-to-save-form-data-to-the-custom-table-in-magento-2/

5
  • and then? if i want to insert those values in my custom tables how can i make this connection between controller and model? Aug 2, 2017 at 7:56
  • Yes refer below link it will give exact idea how you need to manage db connection with your custom module , you need to create model , resource model and its collection , in collection file you need to mention db name and its id Aug 2, 2017 at 7:57
  • thank you for the answer, now i can take my variables into my controller, but in your link i can't find nothing how the model and resource model should look like. Aug 2, 2017 at 8:13
  • @AlinLupoiu , for model and resource model setup use this link - mageplaza.com/magento-2-module-development/… Aug 2, 2017 at 8:16
  • @AlinLupoiu you can also refer this one - jutesenthil.wordpress.com/2016/04/06/… Aug 2, 2017 at 8:17
3

In custom phtml, form action you have to give your controller url.

Below is the example :

<form name="form_sample" id="form_sample" enctype="multipart/form-data" action="<?php echo $this->getUrl() . 'sample/index/save'; ?>" method="post">

In controller, you can get the value and save into the db.

Example:

//Getting the form values

$data = $this->getRequest()->getParams();

//Save into db

$model = $this->obectManager->create('vendor/modulename/model/sample');
$model->setData($data);
$model->save();

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.