by
faheem on February 13th, 2010
You may have heard about FPDF, TCPDF. These are used to generate PDF document in PHP. But very few of you may have heard about LiveDocx, can be found here http://www.livedocx.com/. The most cool news I’m going to tell you that Zend Framework 1.10.0 provides clean and simple interface to LiveDocx API. LiveDocx is soap based service. If you are interested more in LiveDocx, following the link I’ve already provided you.
In this article I am gonna tell you how to create word processing documents and PDF using Zend_Service_LiveDocx. I am sure you will find it very helpful.
You can create you desired document by following these two steps.
1) Create template file
2) Fetch records from your database, as you usually do and assigned them to the template.
1) Creating template file
You can create your template file using Microsoft Word, openOffice and save then as .doc or docx or .rtf format. Keep in mind that creating template file in MS Word and openOffice may differ. In my example I am using Microsoft Word.
Open Microsoft word and create new document.
Before creating the document, I want to show you the resultant template that I’ve created for this example is bellow.

The sign “I” at the stat and end means that I want to repeat this block many time.
And the result file, populated with the data will like this.

Now as you have opened and created document, move forward and insert table as I have inserted in the above example. Put [ in the first row and then click “Insert” in you menu bar and click “Field”. This will open up the following dialog.

Select “Mail Merge” from the “Categories” dropdown and select “MergeField” as show in the following screenshot.

in the “Field name” textbox write “pkey” as show in the following diagram.

Insert all your “MergeField” in the document and create the document you desired. Now if you want to repeat entire block you’ve created or part of it, click at the beginning of that block and select “Insert” form your menu bar and click “Bookmark” as shown in the following diagram.

This will open the following dialog.

I’ve written “blockstart_issue” in the “Bookmark name” text field and pressed “Add” button. Now go to the end of the document or the block you want to repeat, and insert another bookmark using the same method discussed above. But this time the name must be “blockend_issue”. The start bookmark must be like “blockstart_example” and end bookmark should be named “blockend_example”. You can place any text in place of “example” as I’ve put “issue” in my case.
Now as you have defined your template, save it at appropriate place.
2) Fetch records from you database, as we usually do and assigned them to the template.
You have successfully created template file, now its time to instantiate Zend_Service_LiveDocx in your controller as
$phpLiveDocx = new Zend_Service_LiveDocx_MailMerge();
$phpLiveDocx->setUsername("username")
->setPassword("password");
Keep in mind that Zend_Service_LiveDocx is based on soap service, so you will need to get register at http://www.livedocx.com/. When you register with the username and password you will need to set your username and password in place of username and password in theabove two lines.
Next step is to assign values to “MergeField”, you defined while creating your template file. This can simply be done as
$phpLiveDocx->assign(‘pkey’,’TC-4’);
But as I have put bookmarks at the start and end of the entire block, it means that I want that the entire block be repeated for me. So I will first create an associative array as
$issuesData = array(
array (
‘pkey’ => ‘TC-6’,
‘summary’ => ‘Pagination not working in administration area’,
‘created’ => ‘2010/2/12’
……….
…….
)
array (
‘pkey’ => ‘TC-7’,
‘summary’ => ‘Validation not working’,
‘created’ => ‘2010/2/12’
……….
…….
)
);
And now assign this associative array as
$phpLiveDocx->assign(‘issue’, $issuesData);
Here issue is what we defined at the time of putting merge fileds “blockstart_issue” and “blockend_issue”
When you assign data to your “MergeField”, you will need to retrieve the desired document by the following statements.
$document = $phpLiveDocx->retrieveDocument('doc');
unset($phpLiveDocx);
Once the document is generated using the above statement, defined appropriate header and print the created document. I’m using the following statement.
header("Content-Type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=report.doc");
print $document;
Note: Bookmark will not be visible when you put them in your template. In order to view them select “Tools” from menu bar and then “Options”. Check bookmark checkbox in the view tab in the popup dialog.
by
faheem on February 1st, 2010
10 minutes ago I downloaded Zend Framework’s latest version 1.10.0. I was using 1.7.8 for developing open source bug tracking application.
I was already aware of the change made to autoloader, but I didn’t make auotloader work for me in the first attempt. I was unable to load my models and forms.
I was using the following code for autoloading my models, forms and zend framework components.
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
and then setting my include path as
set_include_path(
APPLICATION_PATH . '../../../library'
. PATH_SEPARATOR . APPLICATION_PATH . '/../application/models'
. PATH_SEPARATOR . APPLICATION_PATH . '/../application/forms'
. PATH_SEPARATOR . get_include_path()
);
When I replace loader code with the following code
require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
I encounter an exception saying that loader is unable to load my models. Googling for a bit of time I found the solution.
Actually Zend_Loader_Autoloader is a namespace-based autoloader. By default, it only registers the Zend_ and ZendX_ namespaces.
so it won’t load classes from your own directories.
To force loader to load your classes you will need to write the following statement right after the initialization of your loader.
$autoloader->setFallbackAutoloader(true);
Including this statment will not only load your model, but also pear packages if used in your code. I wonder you wont be able to use pear packages without writting this statement.
Another exception that I wasn’t expecting was file decorator exception. I’m using Zend_From_File for uplaoding files. As soon as I browse my page using Zend_From_File component, i was told that i am not uisng file decorator, I was setting decorator to my file element as
$file1->setDecorators(array(
'viewHelper',
array('Description', array('tag'=>'', 'escape'=>false)),
array(array('data'=>'HtmlTag'),
array('tag'=>'td', 'valign'=>'top', 'style'=> 'background-color:#ffffff;text-align:left')),
array('Label', array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr'))
));
After googling my issue I found that I will need to enclude Zend_Form_Decorator_File with file elements. The changes I made are
$file1->setDecorators(array(
'File',
array('Description', array('tag'=>'', 'escape'=>false)),
array(array('data'=>'HtmlTag'),
array('tag'=>'td', 'valign'=>'top', 'style'=> 'background-color:#ffffff;text-align:left')),
array('Label', array('tag'=>'td')),
array(array('row'=>'HtmlTag'), array('tag'=>'tr'))
));
By comparing the codes above you will find that I have only replaced “viewHelper” with “File”.
by
faheem on July 13th, 2009
In my previous posts I discussed how to create accordion container holding accordion panes and border container having content panes.
In this article I am going to show you how easy it is to create tab continer that hold contents panes. Each content pane having different contents. Contents in one tab pane are shown at a time. when use click on the tab pane’s title, contents in that tab pane are shown.
Before reading this post, you better read and implement what I have discussed in my article “Zend Framework and Dojo: configuration”. Before creating tab continer and panes, you will need to understand and perform necessary configuration.I assume that you have read the post I have mentioned and have done the necessary configuration. Now let’s get started.
First of all, you will need to create your controller as
class ContainerController extends Zend_Controller_Action
{
public function tabAction()
{
}
}
In the code above we have defined our ContainerController extending it from Zend_Controller_Action, and then we have defined our tabAction.
Now, the next step is to create tab.phtml in /application/views/scripts/container/ and place the following code in it.
$this->tabContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px'
));
echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'width: 200px; background-color: white;')
);
echo $this->contentPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'about',
'Information about your company etc',
array('region' => 'bottom', 'title'=>'About Us'),
array('style' => 'background-color: white;')
);
echo $this->tabContainer()->captureEnd('main-container');
?>
We first call captureStart() method of tabContainer() dojo view helper, giving it an id, and array containing tab container special attributes. Next we define content panes. Each content pane holds the data. The contents panes in the tab container will become tab panes.
each content pane is defined as
echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
Here “home” is the id of the content page, Next “string” is the contents that will appear in the tab pane. Next we have defined the array of the special attributes of the contents. Here title is the most important attribute. This title will appear on the tab. The last array contain css related attributes.
That’s it. we have now written all necessary code for creating nice and beautiful Tab container.
Cheers.
by
faheem on July 13th, 2009
You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.
1. Inner Join
The simplest query will be
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->order('column name ASC/DESC');
2. Left Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
3. Right Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
4. Full Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
Once you write these queries, you can fetch a single row or multiple rows as
$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select)
The first statement fetch only one row, while the second statement fetch the entire dataset.
by
faheem on July 12th, 2009
In my previous artilce I discuss how to create accordion container and panes. If you wish to create accordion container and panes, read my article “Creating dojo accordion Container in Zend”.
If you don’t know how to configure dojo and Zend Framework, read here.
In this article, however I am going to discuss how to create border container. Border continer divide our page in different section so that we can display different contents in those sectitons.
To create the border container we first need to create our controller as
class ContainerController extends Zend_Controller_Action
{
public function borderAction()
{
}
}
Now in your /application/views/scripts/container/border.phtml, place the following code.
$this->borderContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px',
'align' => 'center'
));
echo $this->contentPane(
'menuPane',
'This is the menu pane',
array('region' => 'top'),
array('style' => 'background-color: darkblue;color:white')
);
echo $this->contentPane(
'navPane',
'This is the navigation pane',
array('region' => 'left'),
array('style' => 'width: 200px; background-color: lightblue;')
);
echo $this->contentPane(
'mainPane',
'This is the main content pane area',
array('region' => 'center'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'statusPane',
'Status area',
array('region' => 'bottom'),
array('style' => 'background-color: lightgray;')
);
echo $this->borderContainer()->captureEnd('main-container');
Here we have called captureStart() method to start our border container, and then we have placed different content panes.
Each content pane has an “id”, “contents” it holds, array containing content panes attributes, and an array containing css attributes.
by
faheem on July 12th, 2009
Dojo provide very easy and nice way of creating different containers such as accordion, tab, border, and stack etc.
These containers hold different type of panes. These different panes in turn use to hold contents. contents can be simple text or it can be complete html.
Zend Framework collaboration with Dojo has made things quite easy. Zend Framework provide view helpers to achieve different type of dojo functionality.
In this article I am going to discuss how to create Accordion Container. accordion Container hold accordion panes. Each accordion pane hold different contents and open in a stylish way when user click on the title of the pane.
In order to enable dojo helpers in you Zend Framework application, you will need to make some initial configuration. read my tutorial “Zend Framework and Dojo: configuration” before reading this tutorial. After successfull configuration create a controller called “ContinerController.php” in your controllers directory and place the following code in it.
class ContainerController extends Zend_Controller_Action
{
public function accordionAction()
{
}
}
We have only defined an action in our controller, putting no code at all. you however can put whatever code you wish.
Now in /application/views/scripts/container/accordion.phtml place the following code.
$this->accordionContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:400px'
));
echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
echo $this->accordionPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'background-color: white;')
);
echo $this->accordionPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);
echo $this->accordionContainer()->captureEnd('main-container');
The code is pretty simple. we first call captureStart() method on accordionContainer(). this will start accordion container for us.
Once the accordion continer is started, we need to put accordion panes in it and at the end we will need to call captureEnd() method to end our accordion container.
The container holding the following accordion pane.
echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
The above code call accordionPane() helper method. This dojo helper method take an “id”, “contents” to be displayed in the accordion pane, an array containing the special attributes of the accordion pane, and array of css attributes.
by
faheem on July 12th, 2009
Well, while working with ajax, it better to have an xml as response. Xml, however need more coding and parsing on client side than json.
Zend framework provides very easy way to generate json response.
In this article I’m going to discuss how to create Ajax request using prototype and how to use Zend_Json to generate response.
For generating Ajax request, you will need to write
If response is the form of this
[
{"firstName":"Faheem","lastName":"Abbas","username":"fahim","email":"faheem.abbas@example.com"},
{"firstName":"Shazil","lastName":"Hassan","username":"shazil","email":"shazil.hassan@yahoo.com"}
]
Then to acess the values of the first row, write
var firstName = results[0].firstName;
var lastName = results[0].lastName;
and the values of the second row can be accessed as
var firstName = results[1]. firstName;
var lastName = results[1].lastName;
To create Json response, you will need to write the following in your controller action
$users = new Users();
$username = $this->_getParam('username');
$select = $users->select();
$data = $users->fetchAll($select);
$results = $data->toArray();
echo Zend_Json::encode($results);
Keep in mind that “users” is our model, having the following code.
class Users extends Zend_Db_Table
{
protected $_name = "users";
}
That’s it. cheers.
by
faheem on July 10th, 2009
Joomla is a nice CMS(content management system) and Zend Framework is once of the famous and widely adopted MVC Framework since its first release. One of the nice thing about Zend is its loosely coupled components.
Keep in mind that component in joomla and Zend Framework don’t refer to the same concept. Those who have worked in Joomla and Zend Framework know the difference.
In this article I’m not going to discuss what Zend and Joomla are all about and how component is different in both, but instead I’m going to share a little secret of how to develop joomla component in Zend Framework.
This article is not for those who are unaware of joomla and Zend.
Although joomla has own API for developing its components and modules, but you can use any php code in addition to its own API.
Reason is simple. Joomla is developed in php.
As Zend also used php behind the scene, so both can interact easily.
This was a bit of introduction.
While discussing all these things I assumed that you have little knowledge of joomla and have some knowledge of Zend Framework as well.
So let’s dig in.
Before writing any code you will need to successfully download and install joomla. Also download Zend and save it in the directory of your choice.
Once successfully installed joomla, open joomla/administrator/components and create a folder called com_yourcomp.
This is your component folder. You will need to create a file named yourcomp.php
If you want to add component in your administrator, the name should be admin.yourcomp.php.
That’s it, you have now created a the necessary directory structure for your joomla component development.
If you write a line “Hello world!” in youcomp.php or admin.yourcomp.php and browse your page as
http://localhost/joomla/index.php?option=com_yourcomp
you will see
“Hello world” printed.
These are the minimum requirements for developing joomla component.
Now we will using Zend Framework classes to add code to this file plus we will create Zend directory structure in order to work with Zend MVC.
Create following directory structure in your joomla/administrator/components.

Here you can see that my component name is com_advertisers.
In this directory I’ve
* admin.advertiser.php file
* application directory
* Joomla directory
The file admin.advertiser.php will serve as the bootstrap file.
Application directory contain specific directory for controllers, models and views.
The most important role is played by our Joomla directory in developing joomla component in Zend Framework.
This directory contain Controllers/Plugins/Router.php file.
This file contains code for calling specific action based on particular task. Before going to discuss code in the Router.php file, I’m going to show the code need in our admin.advertisers.php file.
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/'
. PATH_SEPARATOR . ROOT_DIR . '/application'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . get_include_path()
);
require_once "Zend/Controller/Front.php";
require_once "Joomla/Controllers/Plugins/Router.php";
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->registerPlugin(new Joomla_Controllers_Plugins_Router());
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
In the first few lines I have included path to our com_advertisers directory, application directory and models directory.
Next I include Zend Front Controller files and Router.php file. I’ll discuss code in the Router.php file later as it contain the most important code.
Next I initialize front controller, register Router Plugin class which is defined in our Router.php file, set controller directory and call dispatch.
That’s it. We have now defined our bootstrap file.
One important thing is setting path to our library files that contain Zend component.
You can include path using set_include_path or set it in your php.ini file.
If you don’t include this path, your application will not work as you expected.
Now go to controllers directory and create IndexController.php and write the following code in it.
require_once('Zend/Controller/Action.php');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function editAction()
{
}
public function saveAction()
{
}
}
Noting special here. I’ve created only three actions.
Go to your application/views/scripts directory and create directory called index and create three files index.phtml, edit.phtml and save.phtml.
The code above is what you will need to work with Zend Framework MVC. In order to integrate this code with joomla will need one additional files. In my case the file is Router.php
I have create this file in com_advertiser/Joomla/Controllers/Plugins/ directory.
The code contain in this file is
require_once('Zend/Controller/Plugin/Abstract.php');
class Joomla_Controllers_Plugins_Router extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$task = $request->getParam('task')
switch($task) {
case 'edit':
$request->setActionName('edit');
break;
case 'save':
$request->setActionName('save');
break;
default:
$request->setActionName('index');
break;
}
}
}
First I’ve include plugin class and then extended my Router class from Zend_Controller_Plugin_Abstract.
This Zend_Controller_Plugin_Abstract class contain a method preDispatch that is called before any controller is called in the routing process.
In the preDispatch method, I get the param “task” and write a switch statement to check this param. If it is edit, I give control to my editAction of the default IndexController. And similarly if it is save, I route request to my saveAction and by default, if no parameter is specified, the request will be dispatched to indexAction of my IndexController.
That’s it.
Now if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=save
It will show what ever you have written in your save.phtml file.
And similarly if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=edit
it will route you to editAction and will display whatever you have define there.
Any question and suggestion are welcomed.
by
faheem on July 6th, 2009
Zend_Config is used to simply access to, and use of configuration data in Zend Framework application.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => localhost',
'username' => 'user_name',
'password' => 'user_password',
'dbname' => 'database_name'
)
)
);
You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
$config = new Zend_Config($configArray);
Now, if you want to make database configuration, simply write
$db= Zend_Db::factory($config->database);
To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.
[development]
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user_name
database.params.password = user_password
database.params.dbname = database_name
After defining ini file, simply write
$config = new Zend_Config_Ini(‘path/to/ini/config.ini’,’ development’);
in your application.
The database configuration is same as we done earlie
$db = Zend_Config::factory($config->database);
Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
< development >
pdo_mysql
db.example.com
dbuser
secret
dbname
development >
Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
$db = Zend_Db::factory($config->database);
That’s it. cheers.
by
faheem on July 6th, 2009
Zend Framework Form: working with radio buttons
I have already discussed creation of Zend_From in my previous articles. In this article I’d discuss how to work
with radio buttons in Zend Framework Form.
In your Zend_Form, radio buttons can be created using two methods.
The first one is
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');
$gender = $this->createElement('radion','gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}
In the above code we first create our form by extending it from Zend_Form, override its init() method and setting its method and action attributes.
Next we create our radio button as
$gender = $this->createElement('radion','gender');
Here first argument specify that we want to create radion button element of the form and the second argument set the name
and id of the radio button element group. In the next line we call addMultiOptions() method giving its array of optional
values. and lost but not least, I am calling method setSeparator for placing both radio buttons on the same line. If this
setSeparator method is not called, each radion button will appear on separate line.
The above radio button can also be created as
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('user/process');
$gender = new Zend_Form_Element_Radio('gender');
$gender->setLabel('Gender:')
->addMultiOptions(array(
'male' => 'Male',
'female' => 'Female'
))
->setSeparator('');
}
}
The only difference in the above two example is that I have placed
$gender = $this->createElement('radion','gender');
With
$gender = new Zend_Form_Element_Radio('gender');
Both statements give the same result.
For setting different radio button options, you can also use the following method.
$gender->addMultiOption(‘male’,’Male’);
$gender->addMultiOption(‘female’,’Female’);