Pregunta

I was looking in implement a form that collect a customers name and email information by writing the information into a CSV file.

I'm completely new to Magento and got help with the following code via my previous question.

I've written a form for the frontend (second code below) but I'm have issues with the post data and how to handle it. I don't think the form is working because I'm not handling the information correctly.

As you can see I tried creating a CSV file named 'getfirmwarecustomerinfo.csv' in the module's controller (wasn't sure whether I was supposed to use $this->getRequest()->getPost() or $this->getRequest()->getParams().

The person who helped mentioned adding information mentioned I need code to validate post data and to save post data to CSV file.

app/code/local/Myname/Mymodule/controllers/IndexController.php

<?php

class Myname_Mymodule_IndexController extends Mage_Core_Controller_Front_Action {

    public function saveAction() {
        $postData = $this->getRequest()->getPost();
        //$params = $this->getRequest()->getParams();
        $file = fopen('getfirmwarecustomerinfo.csv', 'w');
        $info = array($postData['firstname'], $postData['lastname'], $postData['useremail']);
        fputcsv($file, $info);
        fclose($file);

        header("Content-type: text/csv");
        header("Content-disposition: attachment; filename = getfirmwarecustomerinfo.csv");
        readfile("getfirmwarecustomerinfo.csv");

        // afterwards, show a nice message & redirect the user to the previous page
        $session = Mage::getSingleton('core/session');
        if($success) {
            $session->addSuccess(Mage::helper('myname_mymodule')->__("IT WORKED"));
        } else {
            $session->addError(Mage::helper('myname_mymodule')->__("Something went wrong."));
        }

        $this->_redirectReferer();
    }
}

For the frontend, I found this piece of code from Inchoo. Most of the code is the same, I just added the <?php echo $this->getUrl('myname_mymodule/index/save', array('_secure'=>true)) ?> but I'm still not sure how the two files are connected?

app/design/frontend/base/default/templates/myname_mymodule/form.phtml

<form name="test-form" id="my-custom-form" action="<?php echo $this->getUrl('myname_mymodule/index/save', array('_secure'=>true)) ?>" method="post">
  <label for="firstname"><?php echo $this->__('First name') ?> <span class="required">*</span></label><br />
  <input id="firstname" name="firstname" class="input-text required-entry" /><br />

  <label for="lastname"><?php echo $this->__('Last name') ?> <span class="required">*</span></label><br />
  <input id="lastname" name="lastname" class="input-text required-entry" /><br />

  <label for="useremail"><?php echo $this->__('Email') ?> <span class="required">*</span></label><br />
  <input type="text" name="useremail" id="useremail" class="input-text required-entry validate-email" /><br />

  <input type="submit" name="submit" value="<?php echo Mage::helper('contacts')->__('Submit') ?>" />
</form>
<script type="text/javascript">
  //< ![CDATA[
      var customForm = new VarienForm('my-custom-form');
  //]]>
</script>

Any explanation of what I'm doing wrong would be appreciated!

¿Fue útil?

Solución

Ok, it's me again.

It's actually pretty easy: Magento uses a (slightly modified) MVC pattern. This means that a URL is "translated" into a controller classname. From this classname, Magento "translates" the name of the file it should include in its autoloader, and includes that file.

Each controller class must implement one or more methods like function blablablaAction(), in your example the saveAction(). When you call a URL like, say myname_mymodule/index/save, Magento will look into your config.xml file where you defined the <route>, then translate that to your controller "base classname" (Myname_Mymodule_*), then add the second part of the URL ("index") and come up with a controller class Myname_Mymodule_IndexController, which it tries to load from app/code/[codePool]/Myname/Mymodule/controllers/IndexController.php. The last part of the URL ("save") then determines that Magento tries to call the saveAction()

So far for the connection of these files.

In your code I see that you are setting a header() manually - no need to do that. Also, my advice regarding "validation" was more general, such as, if you received a string entered by a user, you should of course validate it.

I assume your saveAction() gets executed?

So, just du something like this:

public function saveAction() {
    $postData = $this->getRequest()->getPost();
    $csvHandle = fopen("path/to/csv", "r+");
    // validate the data to make sure that nobody enters Code in the form, and your email address is actually an email address, etc.
    fputcsv($csvHandle, $postData, ";", '"');
    // (depending on your chosen delimiter)
    // here proceed with my code from last answer
}

Magento sets all the headers for you. Also, in my last answer, I included code to set a nice message to the user, and redirect him to the page where he came from.

If it still does not work, make sure you have DeveloperMode enabled (do it in index.php, or SetEnv in .htaccess / Apache config) which will cause every small error to throw an exception. And also look under magento-root/var/log to see if there are system.log or exception.log files (if logging is enabled in the backend).

By the way, read this: https://alanstorm.com/category/magento/ to understand Magento. Just care that you only read the Magento 1 stuff, because Magento 2 is a bit different.

Update after comments

Ok, sorry - maybe I didn't get the getUrl() part for the form action right. If you are sure your module is active, you might want to ask another question here on how to call the correct URL based on your config.xml. I always mess this up in the first try and have to "test" until I get the path correct :/

Regarding the saveAction() (case-sensitivity is important), and if it creates a "page": You should read into the MVC structure of Magento, e.g. here is a flowchart: https://alanstorm.com/2009/img/magento-book/magento-mvc.png and there are some good answers out there for this - I have already mentioned Alan Storm's blog.

The method saveAction() simply "answers the request". It does not use a layout and blocks ("View" in MVC), so it does not create a page. Yes, this is what the _redirectReferer() part is for, but you can simply change this to a redirect to another URL as you wish.

Regarding the error message: The addSuccess() and addError() methods in my code will show messages to the user. They are stored in the session (so they will survive the redirect) and will be shown on the next page (as long as it belongs to the Magento shop). If you want to use javascript-validation for your form, this is a different topic, but it has already been answered here on MagentoSE and Magento has an easy-to-use framework for it where you simply add HTML-classes to your input elements - simply use Google :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top