Sunday, September 22, 2013

How to include view(.phtml) file in another view file

In the view file,insert below line where you want to include .phtml file in another view file.

<?php echo $this->partial('index/leftmenu.phtml', 'module'); ?>

As per our example -

You have to create the leftmenu.phtml in views/index folder, where index is the controller name. You can specify the module as the second parameter.If you are working on "application" default module then no need to pass second parameter.

you can simply write like this  

<?php echo $this->partial('index/leftmenu.phtml');?>   

Monday, July 15, 2013

Change meta tags in zend framework layout

Steps to change meta tags in zend framework layout

It would recommend setting a view variable for the keywords. For example, in your bootstrap.php you could define default keywords as follows:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function _initDoctype() {

        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $viewRenderer->setView($view);
        $view->headTitle('Techinfo Tricks Solutions')->setSeparator(' :: ');
        $view->keywords = 'Techinfo Tricks Web Solutions';

    }

In layout.phtml we would have then:

<?php echo $this->headMeta()->appendName('keywords', $this->keywords); ?>

Finally, in your views (or actions) you could change the Meta keywords simply by changing the keywords view variable:

// in an action
$this->view->keywords = 'new kewords';

//or in a view
<?php $this->keywords = 'new kewords'; ?>



For example some thing like this

public function aboutusAction()
{
       $this->view->keywords = 'About US';

Setting a default page title in Zend Framework and modifying per action

Specifying the Page Title

The site or business name as part of the page title and then we are adding additional information based on the location or page within the site. As an example, the techinfotricks.com website includes the string " techinfotricks.com " on all pages, and the prepends information based on the page: "About US - techinfotricks.com ". Within Zend Framework, the headTitle() view helper can help simplify this task.

The headTitle() helper allows you to aggregate content for the <title> tag.

You can control the order using prepend() and append(), and provide a separator to use between segments using the setSeparator() method.

Typically, you should specify any segments common to all pages in your bootstrap, similar to how we define the doctype. In this case, we'll define a _initPlaceholders() method for operating on all the various placeholders, and specify an initial title as well as a separator.

    class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
    {
        // ...    
        protected function _initDoctype()
      { 
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $viewRenderer->setView($view);
        $view->headTitle('Techinfo Tricks Solutions')->setSeparator(' :: ');
       }
        // ...
    }

Within a view script, we might want to add another segment:

// place after other segments
<?php $this->headTitle()->append('Some Page'); ?>
   
// place before
<?php $this->headTitle()->prepend('Some Page'); ?>


In our layout, we will simply echo the headTitle() helper:
<?php echo $this->doctype() ?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <?php echo $this->headTitle(); ?>        
        <link rel="stylesheet" type="text/css" href="<?php echo $this->baseUrl('css/stylesheet.css'); ?>" />           </head>
    <body>
       .............................
       .............................
       .............................
    </body>
</html>

This will generate the following output:
    <!-- If append() was used: -->
  <title>Techinfo Tricks Solutions :: Some Page</title>
    
    <!-- If prepend() was used: -->
<title>Some Page :: >Techinfo Tricks Solutions </title> 

Another way to modifying the title in the action on controller.

public function aboutusAction()
{
    $this->view->headTitle()->prepend('About US');
}
 

This will generate the following output:

<title> Techinfo Tricks Solutions :: About US</title>




Monday, July 8, 2013

Authenticating Users in Zend Framework


Authentication example

First create a table in your database by executing the following sql query.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `status` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Next step to create a model against this table in your application/model/ directory.

I am creating Users.php and writing the following code in it.

    <?
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    /** Table name */
    protected $_name    = 'users';
    protected $_primary = 'id';      
}
    ?>


Now create a controller named AuthController.php in application/controllers/ directory and place the following code in it

class AuthController extends Zend_Controller_Action

{

    public function loginAction()
    {
    }  
    public function logoutAction()
    {
    }
    public function homeAction()
    {
    }
}


Now create templates files for actions. Go application/views/scripts and create a folder named “auth” and create three files in application/views/scripts/auth named

    login.phtml
    logout.phtml
    home.phtml



In LoginForm.php, write the following code

<?php
class Application_Form_LoginForm extends Zend_Form
{
    public function init()
    {
        $username = $this->createElement('text','username');
        $username->setLabel('Username: *')->setRequired(true);
               
        $password = $this->createElement('password','password');
        $password->setLabel('Password: *')->setRequired(true);
               
        $signin = $this->createElement('submit','signin');
        $signin->setLabel('Sign in')->setIgnore(true);
       
        $this->addElements(array($username,$password,$signin,));
    }
}
?>


So in AuthController.php, write the following code

<?php
class Admin_AuthController extends Zend_Controller_Action
{
    public function homeAction()
    {
        $this->_helper->layout->setLayout('admin');
        $storage = new Zend_Auth_Storage_Session();
        $data = $storage->read();
        if(!$data){
            $this->_redirect('admin/auth/login');
        }
        $this->view->username = $data->username;               
    }
   
    public function loginAction()
    {
        $this->_helper->layout->setLayout('admin');       
        $form = new Admin_Form_LoginForm();
        $this->view->form = $form;
        if($this->getRequest()->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                $auth = Zend_Auth::getInstance();
                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('users')
                            ->setIdentityColumn('username')
                            ->setCredentialColumn('password');
                $authAdapter->setIdentity($data['username'])
                            ->setCredential($data['password']);
                $result = $auth->authenticate($authAdapter);
                if($result->isValid()){
                    $storage = new Zend_Auth_Storage_Session();
                    $storage->write($authAdapter->getResultRowObject());
                    $this->_redirect('admin/auth/home');
                } else {
                    $this->view->errorMessage = "Invalid username or password. Please try again.";
                }        
            }
        }
    }
       
    public function logoutAction()
    {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        $this->_redirect('admin/auth/login');
    }   
}
?>


open views/scripts/auth/home.phtml and write the following code.

    Welcome <?=$this->username?>,<br>

    Home page content .......
    .....
   <br>
 
  <a href=”<?=$this->url(array(’controller’=>’auth’,'action’=>’logout’))?>”>Logout</a>

Login functionality is get ready to use.


Friday, July 5, 2013

Hide controller name from URL


To override your default route and prevent you from visiting controllers and modules that are opened via

URLs

like: example.com/controller/action to example.com/action

Place below mention code in your /application/Bootstrap.php file:

public function _initCustomRoute()
{
    $router = Zend_Controller_Front::getInstance()->getRouter();
    $route = new Zend_Controller_Router_Route(':action', array(
        'module'     => 'default',
        'controller' => 'index'
    ));
    $router->addRoute('default-override', $route);

}

Thursday, June 27, 2013

How to use multiple layouts with different action in Zend Framework

First create alternate layout

/path/to/application/views/layouts/scripts/layout.phtml --> default layout

/path/to/application/views/layouts/scripts/admin.phtml --> admin layout

The Default layout name set in application.ini

resources.layout.layoutPath = APPLICATION_PATH “/layout/script”
resources.layout.layout = “layout”

here layout mean you have one layout.phtml file in your layout folder.

So to use different layout ,you need to create another layout file in your layout folder as admin.phtml

$this->_helper->layout->setLayout('admin');

Now you can call your alternate layout with above mention function on controller.


Full example

<?php
class IndexController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */      
    }
    public function indexAction()
    {
        $this->_helper->layout->setLayout('admin');  //set alternate layout
    }
    public function userlistAction()
    {
        //default layout will be called
    }
}

Modular applications with Zend Framework 1.11

STEP 1 –

Create folder with name “modules” under your “application” folder.

STEP 2 –

Then under “modules” folder you can create folder with your module name for example suppose we are going to develop separate module for Administrator so module name should be “admin”.

Now your file structure should be something like this.




STEP 3 –

Rest of programming and folder and file structure should be same we have on our default setup of zend framework  on “application” folder.

But now your class name should be with prefix of module name.

For example – Our example module is “admin”

Then class name should be like  this–

Admin_UserController, Admin_Model_UserModel, Admin_Form_LoginForm, etc.

But file should be save with name “UserController.php” if we taking an example of controller.


STEP 4 –

We now have to make changes on “application.ini” file to make sure Zend is aware of that module
application.ini :
Append following lines.

resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.defaultModule = "default"
resources.modules[] = ""



STEP 5 –

Again, the naming is important; the class name must be [module name]_Bootstrap and it must extend Zend_Application_Module_Bootstrap.Finally add a Bootstrap class to the module:

It must be stored in a file called Bootstrap.php within the root of the module.

<?php

class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{
       public function _initAutoload()
        {
            // Each module needs to be registered...
            $modules = array(
                'Admin',               
            );

            foreach ($modules as $module) {
                $autoloader = new Zend_Application_Module_Autoloader(array(
                    'namespace' => ucfirst($module),
                    'basePath'  => APPLICATION_PATH . '/modules/' . strtolower($module),
                ));
            }

            return $autoloader;
        }
}


The module is now ready to go.

Tuesday, June 25, 2013

Dojo Integration / configuration with Zend Framework


You can download Dojo library from its official site http://dojotoolkit.org/download/

Step 1:- 

The first and most important step is to copy external ”dojo”  into your root folder of site.

Your file structure some thing like this after copied dojo folder.

Step 2:- 

After you copy the dojo folder add the following code in your bootstrap file.

$view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');


Means you have to add path to Dojo view helpers on your bootstrap file.

After changes your bootstrap contain following lines.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    protected function _initDoctype()
    {
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
        $view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $viewRenderer->setView($view);
    }   
}

Step 3 :-

Next you would need to add path to dojo.js file and other module of the dojo toolkit.

So open your layout file and put following code.

 <?php
        $this->dojo()->setDjConfigOption('usePlainJson', true)
                ->addStylesheetModule('dijit.themes.tundra')
                ->setLocalPath("http://localhost/zend/dojo/dojo/dojo.js");
        echo $this->dojo();
 ?>

The only thing you need to do is to enable dojo in your template file.


Your configuration is now completed.

Now create your form as follows.

Dojo Editor example after configuration 

<?php
class Application_Form_Inquery extends Zend_Form
{
    public function init() {
        
        // Dojo-enable the form:
        Zend_Dojo::enableForm($this);         
        
        // Dojo-enable all sub forms:
        foreach ($this->getSubForms() as $subForm) {
            Zend_Dojo::enableForm($subForm);
        }
        
        //parent::__construct($options);        
        
        // Set the method for the display form to POST
        $this->setMethod('post');

        // Add an company name element
        $this->addElement('text', 'company_name', array(
            'label' => 'Company name:',
            'required' => true,
            'filters' => array('StringTrim'),
        ));

        // Add the contact_person_name element
        $this->addElement('text', 'contact_person_name', array(
            'label' => 'Contact person name:',
            'required' => true,
        ));

        // Add the phone_no element
        $this->addElement('text', 'phone_no', array(
            'label' => 'Phone no:',
            'required' => true,
        ));

        // Add the ext element
        $this->addElement('text', 'ext', array(
            'label' => 'Ext:',
            'required' => false,
        ));

        // Add the email element
        $this->addElement('text', 'email', array(
            'label' => 'Email:',
            'required' => true,
        ));

        // Add the country element
        $this->addElement('text', 'country', array(
            'label' => 'Country:',
            'required' => true,
        ));

        // Add the Description element
        /*$this->addElement('textarea', 'description', array(
            'label' => 'Description:',
            'required' => true,
        ));*/
        
        $this->addElement('editor', 'description', array(
            'label'=>'Description',
            //'extraPlugins'            => array('undo', '|', 'bold', 'italic','fontName', 'fontSize', ),
            'editActionInterval' => 2,
            'focusOnLoad'        => false,
            'height'             => '250px',
            'inheritWidth'       => true,
            //'styleSheets'        => array('../dojo/dojox/editor/plugins/resources/editorPlugins.css'),
        ));

        // Add a captcha
        $this->addElement('captcha', 'captcha', array(
            'required' => true,
            'label' => 'Captcha',
            'captcha' => array(
                'captcha' => 'Dumb',
                'wordLen' => 5,
                'timeout' => 300
            )
        ));

        // Add the submit button
        $this->addElement('submit', 'submit', array(
            'ignore' => true,
            'label' => 'Submit',
        ));

        // Add the reset button
        $this->addElement('reset', 'reset', array(
            'ignore' => true,
            'label' => 'Reset',
        ));

        // And finally add some CSRF protection
        $this->addElement('hash', 'csrf', array(
            'ignore' => true,
        ));
    }
}
?>

Friday, June 14, 2013

Remove Public from URL



You have to copy all the files from "public" into the "root" folder of site, like css, jquery or images folders and index.php (you simply put them outside) and then customize your index.php file appropriately, for example:

Old Code:-

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../zend_app/application'));



New Code:-

Modify index.php a little bit

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/application'));

Thursday, March 28, 2013

Getting Started with Zend Framework 2

The objective of blog post is to give idea to build our application or installed ZEND framework 2.0

Go to https://github.com/zendframework/ZendSkeletonApplication and click the “Zip” button.

This will download a file. Unzip this file into the directory where you like to keep and rename according your project name. (For example htdocs or www)

To install Zend Framework 2 into our application simply type:

php composer.phar self-update

php composer.phar install

After executing successfully last command

you will get following output “Generating autoload files”

If error occurs some thing like this “'php' is not recognized as an internal or external command “

TO resolve this error you have to set the PHP path in window environment variable.

From the desktop, right-click My Computer and click Properties. In the System Properties window, click on the Advanced tab. In the Advanced section, click the Environment Variables button. •

Finally, in the Environment Variables window highlight the Path variable in the Systems Variable section and click the Edit button.

Add or modify the path lines with the paths you wish the computer to access.




Set some like this “C:\your\xamp\path\php”

http://localhost/projectname/public/

Now you have a working skeleton application on which you can start adding the specifics for our application.