How to get controller name or action in view or layout

To get the controller name in view or layout use the below function

 $controller = Zend_Controller_Front::getInstance()->getRequest()->getControllerName()

To get action

 $action =  $controller = Zend_Controller_Front::getInstance()->getRequest()->getActionName()


Zend Framework - Get the last url parameter

 In the controller,

   $requestUri = $this->getRequest()->getRequestUri();
   $lastParameter = substr($requestUri, strrpos($requestUri,'/')+1);

Using same view for different modules in zend framework

In the Controller Action we can specify the view path then use helper to load view in the specified folder

class IndexController extends Zend_Controller_Action{

 public function indexAction()
    {
        $this->view->setScriptPath(APPLICATION_PATH.'/modules/modulename/views/scripts/controllername');
           $this->_helper->viewRenderer->setNeverController(true)->setRender('index');
     }
}

I hope there is no default method like $this->_forward('module', 'controller', 'action')

Using Zend Auth Login without using the Zend MVC

We can use the Zend Login for our existing website without using whole Zend Library. Zend Auth module provides the more secure login.

First we need to download the following folders and files from Zend Library
 1. Zend/Db/
 2. Zend/Auth/
 3. Zend/Session/
 4. Zend/Db.php
 5. Zend/Auth.php
 6. Zend/Session.php
 7. Zend/Exception.php
 Then you can use the below code in your login.
require_once('Zend/Db/Table/Abstract.php');
require_once('Zend/Auth/Adapter/DbTable.php');
require_once('Zend/Auth.php');
require_once('Zend/Db/Expr.php');





$params = array(
    'host'     => 'localhost',
    'username' => 'support',
    'password' => 'vanilla',
    'dbname'   => 'Training',
);

try {
    $db = Zend_Db::factory('Pdo_Mysql', $params);
    $db->getConnection();
} catch(Zend_Db_Adapter_Exception $e) {
    die("
There was an error connecting to the server
"); //Probably bad login or mysql daemon is not running.
} catch(Zend_Exception $e) {
    die("
Something failed to load
"); //factory() probably failed to load the adapter class
}
$uname = 'admin';
$paswd = md5($uname);
 $auth       = Zend_Auth::getInstance();
 $authAdapter = new Zend_Auth_Adapter_DbTable($db);
 $authAdapter->setTableName('users')
                   ->setIdentityColumn('username')
                   ->setCredentialColumn('pwd');  
       
       // Set the input credential values
       $authAdapter->setIdentity($uname);
       $authAdapter->setCredential(md5($uname));
   
       // Perform the authentication query, saving the result
       $result = $auth->authenticate($authAdapter);
   
       if($result->isValid()){
        print_r($result);
        print_r($_SESSION);
         echo "Success";
       }else{
         echo "Failure";
       }

How to use MySQL 'RAND()' with limit in with Zend Select Query

  We need to use new Zend_Db_Expr('RAND()') with select query
  Ex: $selectQry    =    $this->util->db->select()->from(array('P'=>$this->_name),array('package_id','name','day_duration','night_duration','price','discount_price'))
                                                    ->order(new Zend_Db_Expr('RAND()'))
                                                    ->limit(2);

Html email using Zend Framework

Create a template in the view /views/scripts/emails/package.phtml
html
body
 echo $this->packageType;
echo $this->details; 
/html

Then in the controller, from which you need to send this use the below code

// create zend view object
$html = new Zend_View();
$html->setScriptPath(APPLICATION_PATH . '/views/scripts/emails/');

// assign the view variables here
$html->assign('packageType', 'Luxure');
$html->assign('details', 'Package inclusions');

// create mail object with utf-8 encoding
$mail = new Zend_Mail('utf-8');

// render view
$bodyText = $html->render('package.phtml');

//Set emaill
$mail->addTo('shaijudavis@gmail.com');
$mail->setSubject('Welcome to Limespace.de');
$mail->setFrom('info@elegantkerala.com','Elegant Kerala');
$mail->setBodyHtml($bodyText);
$mail->send();

How to use MySQL MATCH AGAIST in Zend Framework Query

   We can use MATCH AGAINST with zend select where clause.
   Ex:
  $selectQry    =    $this->db->select()->from(array('D'=>$this->_name))
                                                     ->joinLeft(array('C'=>TBL_CATEGORIES),
                                                         'C.category_id = D.category_id',array('category_id'))
                                                    ->where('D.is_deleted = ?', 0)
                                                    ->where('MATCH(C.name) AGAINST (?)', $txt)
                                                    ->orWhere('MATCH(D.name,D.summary,D.description) AGAINST (?)', $txt)
                                                    ->group('D.destination_id');

How to get request path info in the controller?

To get the request pathinfo use the function $this->_request->getPathInfo() in the controller

How to disable the In Array validator in Zend Form?

When we use multiple select or checkbox option, there is default validator so that the value should not be empty. We can bypass it using the function setRegisterInArrayValidator
 
   Ex: $selCategories = new Zend_Form_Element_MultiCheckbox('categories', array(
                        'multiOptions' => $categories));
         $selCategories->setRegisterInArrayValidator(false);

How to save Log in a text file using Zend Framework

We can do that using Zend Log & Zend Log Writer Stream classes.
Ex:
 $logText        =    'TEST TO LOG THE STRING IN TEXT FILE';
 $stream        =    fopen('/var/www/log/path/filename.txt', 'a');
 if( $stream ){
   $writer        =    new Zend_Log_Writer_Stream($stream);
   $logger        =    new Zend_Log($writer);
   $logger->log($logText,Zend_Log::INFO);
  }

How to redirect in Zend Framework without using standard redirect function

If you want to use Zend redirect without using standard redirect function from controller, you can use the below code in any of the plugin or function.
 $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
  $redirector->gotoUrl('/profile/change-password/')->redirectAndExit();

How to get HTTP REFERER value in Zend Framework

You can get that directly in Controller using the below code
     $requestUri    =    $this->getRequest()->getServer('HTTP_REFERER');
 If you want to get that outside of Controller you can use the Zend Front Contorller class
 $requestUri    =    Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();

How to get method name in controller while we try Zend JSON Service call

 You can use the below code in your controller to get the method name while you try jQuery.Zend.Jsonrpc service call

if($_SERVER['REQUEST_METHOD']    ==    'POST') {
            $data     =    json_decode(urldecode($this->getRequest()->getRawBody()));
            echo $data->method;
}

jQuery.Zend.jsonrpc returns error 'not a function' with cross domain request

There is a chance to retun 'not a function' error in console while we try the remote url.
 You can fix that with the following changes

  1. Use the latest jquery file
  2. Remove the 'content-type' attribute from jquery.zend.jsonrpc.js
  3. Add the property 'crossDomain: true' in jquery.zend.jsonrpc.js with ajax request
  4. Set the header("Access-Control-Allow-Origin: *") in your server script.
 
   I have followed the below url and updated the file with above condition then it works fine.
   http://sourcecodebean.com/archives/creating-a-json-rpc-service-using-zend-json-server/422

How to Reset all the values in Zend Form After Submit

   We can use the reset function to clear all the values in Zend Form
   Ex: $formObt->reset();

How to change Zend DB fetchAll() result Array to Object


 For that we need to use the setFetchMode function.

  Ex:  $stmt = $db->query('SELECT * FROM user');
       $stmt->setFetchMode(Zend_Db::FETCH_OBJ);
        $objs = $stmt->fetchAll();

How to to check mail delivery in Zend Framework

              $mail = new Zend_Mail();
                $mail->setBodyText('This is my test message');
                $mail->setFrom('info@cochinhub.com', 'From Name');
                $mail->addTo('sales@cochinhub.com', 'To Name');
                $mail->setSubject('Add subject here');
                try {
                    $mail->send();
                }catch (Zend_Exception $e){
                    echo $e->getMessage();
                }

How to connect MYSQL Database using Zend Framework

   require_once 'Zend/Db.php';
    $dbConnect = Zend_Db::factory("MYSQLI",
                    array(
                        "host" => "localhost",
                        "dbname" => "my_db",
                        "username" => "dbUserName",
                        "password" => "dbPassword")
    );

MysQL UNION in Zend Framework


$selectQry1 = $this->db->select()->from(array('F'=>$tableName))
        ->join(array('FA'=>$tableName2),
        'FA.form_id=F.form_id',
        array('association_id','association_type', 'object_id'))
        ->where('FA.association_type = ?','user')
        ->where('FA.object_id = ?',mysql_escape_string($this->_userId));   
$selectQry2 = $this->db->select()->from(array('F'=>$tableName))
        ->join(array('FA'=>$tableName2),
        'FA.form_id=F.form_id',
        array('association_id','association_type', 'object_id'))
        ->where('FA.association_type = ?','group')
        ->where('FA.object_id IN ( ? )',$groups);   
$selectQry = $this->db->select()->union(array($selectQry1, $selectQry2), Zend_Db_Select::SQL_UNION_ALL)
         ->group('form_id');

How to get Url parameters in Zend Model, Form or any other Classes

ex: url - http://www.example.com/token/TK_15ada12sada1245ad
 
  Then you can get the token value using the following function.
 
  $token =    Zend_Controller_Front::getInstance()->getRequest()->getParam('token');