Magento – Access input field values from form template in helper/controller classes

ce-1.9.0.1controllershelpertemplate

In a Magento checkout template there is a html tag for payment form:

<ul class="form-list" id="payment_form_testmethod" style="display:none;">
    <li>
     <input class="checkbox" type="checkbox" id="<?php echo $_code ?>_cc_save" name="payment[cc_save]" title="Test" value="1" /> ...
    </li>
</ul>

From the helper class I'm trying to access this input field by:

$payment = Mage::app()->getRequest()->getParam('payment');
$cc_save = $payment['cc_save'];

When the tickbox is ticked and posted, $payment & $cc_save are empty when logged.

This also returns empty data:

$payment = Mage::app()->getRequest()->getPost();

Why does this not work?
How can one access values of input fields from template into helper/controller classes in Magento?

Best Answer

Use this for your reference

  1. Your Form should have an action

Your custom form should have an action field for it. Action attribute determines which controller has to take care of the form action. i e

<form action="<?php echo $this->getUrl('checkout/cart/testPost') ?>" name="test-name" id="custom-id" class="some-class" >
               <!-- your inputs goes here -->
</form>
  1. Use Magento's default validation methods.

You can use magento's default validation methods to validate your custom form. For an example for the above case, your form validation can be carried out by using this javascript

<script type="text/javascript">
    //< ![CDATA[
        var customForm = new VarienForm('custom-id');
    //]]>
</script>

Here custom-id is id of your custom-form. Now magento will validate all inputs under you custom form, provided that it should possess valid class names. For example required class. If magento find this class for any one of input inside your form, it will check then this field is empty or not. If it is empty, Magento will automatically notify it. That means you don't need to do any custom validation codes.

For more information, go to this LINK

  1. Validate your form in appropriate controller

If you check your action attribute of form, it will somewhat look like this http://www.yourdomain.com/index.php/checkout/cart/testPost. This means you need to validate your form in cartController which is defined inside checkout module and exactly in testPost() method.

So in app/code/core/Mage/Checkout/controllers/CartController.php define a new method (our custom method) testPost()

public function testPostAction()
{
    $params =  $this->getRequest()->getParams();

    //other actions comes here
}