I am venturing into the Zend Framework and decided to build a simple application to practice with. The app I am building is a simple calculator that allows a user to add, subtract, multiply and divide two numbers.
I am having trouble retrieving the user input to calculate the answer. When I use Zend_Debug::dump($this->getRequest()->getParams()); in the IndexAction() method it displays the form data correctly on the page, but how do I send the data to the proper Model for processing?
Here is the IndexController.php file:
<?php class IndexController extends Zend_Controller_Action { //initialize calculator form on controller call public function init() { //istantiate Zend_Form object $form = new Zend_Form(); $form->setAction('') ->setMethod('post'); //first number input $num1 = $form->createElement('text', 'num1'); $num1->addValidator('Digits') ->setRequired(true) ->setAttrib('placeholder', 'Enter First Number'); //second number input $num2 = $form->createElement('text', 'num2'); $num2->addValidator('Digits') ->setRequired(true) ->setAttrib('placeholder', 'Enter Second Number'); //math operator select box $op = $form->createElement('select', 'operator'); $op->setRequired(true) ->setMultiOptions(array('1'=>'+', '2'=>'-', '3'=>'X', '4'=>'/')) ->setRequired(true); //add elements to form $form->addElement($num1) ->addElement($op) ->addElement($num2) ->addElement('submit', 'equal', array('label' => '=')); return $form; } public function indexAction() { //render the form view $this->view->form = $this->init(); $this->render('index'); } public function calcAction() { $form = $this->form; $data = $this->getRequest()->getParams(); if ($data->isPost()) { if($data->isValid()) { $calculator = new Calculator_Model; switch($data['operator']) { case $data['operator'] === '1': $ans = $calculator->addNums($data['num1'], $data['num2']); return $ans; break; case $data['operator'] === '2': $ans = $calculator->subtractNums($data['num1'], $data['num2']); return $ans; break; case $data['operator'] === '3': $ans = $calculator->multiplyNums($data['num1'], $data['num2']); return $ans; break; case $data['operator'] === '4': $ans = $calculator->divideNums($data['num1'], $data['num2']); return $ans; break; } } else { return $form->getMessages(); } } } } I tried placing the calcAction() script into the indexAction() method but then the page doesn't render at all. How can I get the user input to the Calculator_Model for processing?
$calculator = new Calculator_Modelshould be$calculator = new Calculator_Model()