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');
 

 

How to remove 'requied' validator from Zend_Form

We can use setRequired() function for that.It's useful when you have to use element in different and one need required field and another is not mandatory
  Ex:
    $element = Zend_Form_Element_Text('phoneNumber');
    $element->setRequired(false);

How to check multi-option Zend Form array values in View

We can get the Multi-option values set in Zend Form  and to compare the values in the view using the following function.
  
   Ex: $multiValues    =    $this->form->getElement('all_roles')->getMultiOptions();
        In the 'all_roles' is the form elememnt name in the Form/

How to add 'default' attribute with url parameter

In the url function first we define the controller, action and parameters. Then we need to add the 'default' attribute or else the url is formed with the existing url in the browser.
 $this->url(array('controller'=>'events','action'=>'view','id'=>1),'default',true);

How to fix the Error 'was not found in hastack'

It's the validator for array elements in the Form and it has default in_array validator.
We can remove that validation using setRegisterInArrayValidator to false
   Ex : $userRoles->setRegisterInArrayValidator(false);

Warning: Select query cannot join with another table

The Zend_Db_Table_Select is  used to constrain and validate so  that it may enforce the criteria for a legal SELECT query. There  may be certain cases where you require the flexibility of the  Zend_Db_Table_Row component and do not require a writable or deletable  row.In such cases you can set 
$select->setIntegrityCheck(false)

How to user WHERE IN clause in Zend Query(Zend_Db_Select)

We don't need to implode the array to use with WHERE.
  $users = array(1,2,3);
  $selectQry    =    $this->db->select()->from(array('FI'=>'TBL_NAME'))
                          ->where('FI.user_id IN (?)',$users);

How to get the base url in Zend form

$view = Zend_Layout::getMvcInstance()->getView();
 $baseUrl    =    $view->baseUrl();

Fatal error: Uncaught exception 'Zend_Loader_PluginLoader_Exception' with message 'Plugin by name 'Headlink' was not found in the registry

 If you get the following error or error similar to that, it causes the issue with the function name that you have used.
     
       Ex; $this->headlink('pathToFile'); It's not correct and shows the error.
       It must be $this->headLink('pathToFile'); ie 'L' must be capital letter.

How to set a Form attribute from controller


   If we have a form used for different purpose and in one of the action you want to set a particular attribute to form object. Then you can do that by setting the attribute value from the controller action page.
   Ex:
     public function addAction()
     {
         $form    =    new Form_User();
         $updateUser=    $form->addUser();
         $updateUser->role->setAttrib('disabled','true');
     }

How to set SMTP mail using Zend Framework

1. First you have to download the Zend Framework library.
      Then place it somewhere in the server with name like library and set the include_path to your working php page
      Ex: set_include_path(get_include_path().PATH_SEPARATOR.realpath(realpath(dirname(__FILE__)).'/library'));
   2. Include Zend_mail  and Zend_Mail_Transport_Smtp file in the file/function
   3. Set/Get the config variables
      Use the following code.
        require_once 'Zend/Mail.php';
     require_once 'Zend/Mail/Transport/Smtp.php';
    
     $config = array('auth' => 'login',
                    'username' => 'info@domainname',
                    'password' => 'password');
               
        $transport = new Zend_Mail_Transport_Smtp('smtpServer', $config);
       
    $mail = new Zend_Mail();
   
    $mail->setFrom('info@domainname', 'DO NOT REPLY');
    $mail->addTo($toEmail, 'Recipient');
    $mail->setSubject('Set Subject');
    $mail->setBodyText('Add Message');
   
    $mail->send($transport);

Zend file upload error - Exceeds the defined ini size

This error can occur due to the following reasons.
       1. Your upload image size is greater than the maximum upload size.
       2. You have not set the attribute enctype=multipart/form-data in the form tag.

fileUploadErrorAttack - File was illegally uploaded. This could be a possible attack

  It occurs when you try to get the File upload data after the Form getValues() function.
  First you have to add code for File upload data then the form values.

  Ex:
     if ($this->getRequest()->isPost()) {
       if($this->formObj->isValid($_POST)) {

               //Form upload section
                   $upload = new Zend_File_Transfer_Adapter_Http();
           
        $upload->addValidator('Count', false, array('min' =>0, 'max' => 1))
                ->addValidator('IsImage', false, 'jpeg,pjpeg,jpg,png,gif')
                  ->addValidator('Size', false, array('max' => '10MB'))
                       ->setDestination('upload_path');

                 try {
               
             $upload->receive();
                    
           } catch (Zend_File_Transfer_Exception $e) {
     
             die('ERROR'.$e->getMessage());
         }
              //Get form values

              $postValues = $this->formObj->getValues();

          }
      }

How to set value for multiple select options in Zend_Form_Element_Multiselect

We can do that using the setValue function by passig array of selected values
Ex:
    $users = new Zend_Form_Element_Multiselect("users");
    $users->setLabel("Users");
    $users->addMultiOptions(array('1'=>'John Smith','2'=>'Aaron Brown','3'=>'David Beckham');
    $users->setValue(array(1,2));
    so the names John and Aaron will be shown as selected.