Showing posts with label Zend Framework. Show all posts
Showing posts with label Zend Framework. Show all posts

Saturday, 24 January 2015

adding elements to form

when we create form element through zend command. it creates the necessary class and extend from Zend_Form. in the init() method when call the $this variable to refer to the form that we have created.

$this

this refers to the class we are in. so if we are in the form class that we have created and we call $this  we will be referring to the class we are in. so in zend we can call any function or method of Zend_Form through through $this->{method name}.
in the similar way we can call other methods if we are in other classes that extends any other Zend Class.

adding elements and attributes to form

$this->setAction('index/users') and $this->setMethod('post')  method will will set the action and method attributes of the form. this will set the form like;

<form action="index/user" method="POST"></form>

$this->{variable name} is use to define a variable. 

Zend provide us with the functionality to create forms elements like text field, password, check boxes, drop down menu etc. 

creating text field.

$this->name = new Zend_form_element_text('{name of text field}');
$this->name = new Zend_form_element_text('Name');
 this will create text element like that;

<input type="text" name="Name" />

creating password field.

$this->name = new Zend_form_element_password('{name of text field}');
$this->name = new Zend_form_element_password('passwordfield');

<input type="password" name="passwordfield" />

creating a checkbox

$this->checkbox = new Zend_form_element_checkbox({name of checkbox},{other options});
$this->checkbox = new Zend_form_element_checkbox('checkbox',array( 'label' => 'mylabel', 'name' => 'myname', 'checkedValue' => 'value1', 'uncheckedValue' => 'value2' ));

<dd id="myname-element">
<input type="hidden" name="myname" value="value2"><input type="checkbox" name="myname" id="myname" value="value1"></dd>

for multiple checkbox we use other method that is;

multiple checkbox creation;

$this->multi = new Zend_Form_Element_MultiCheckbox('name',array(
                'label' => 'mylabel',
               'multiOptions'=>array(
                'student'=>'students',
                'teacher'=>'Teacher',
                'employee'=>'Employee'
                )
        ));


<dd id="name-element">

<label><input type="checkbox" name="name[]" id="name-student" value="student">students</label><br><label><input type="checkbox" name="name[]" id="name-teacher" value="teacher">Teacher</label><br><label><input type="checkbox" name="name[]" id="name-employee" value="employee">Employee</label></dd>

this default styles of the multi-checkboxes are not good, we have to set decorators, we will we Decorators in zend framework later.

Radio Buttons

$this->multi = new Zend_Form_Element_Radio('radio',array(
                'label' => 'mylabel',
               'multiOptions'=>array(
                'student'=>'students',
                'teacher'=>'Teacher',
                'employee'=>'Employee'
                )
        ));

<dd id="radio-element">
<label><input type="radio" name="radio" id="radio-student" value="student">students</label><br><label><input type="radio" name="radio" id="radio-teacher" value="teacher">Teacher</label><br><label><input type="radio" name="radio" id="radio-employee" value="employee">Employee</label></dd>

Select elements

$this->multi = new Zend_Form_Element_Select('select',array(
                'label' => 'mylabel',
               'multiOptions'=>array(
                'student'=>'students',
                'teacher'=>'Teacher',
                'employee'=>'Employee'
                )
        ));

<select name="select" id="select">
    <option value="student">students</option>
    <option value="teacher">Teacher</option>
    <option value="employee">Employee</option>
</select>

Setting labels to the elements;

Adding elements in zend is easy and adding labels to these element almost same for every element. every zend element has a method known as setLabel({name of label });. with that element we can set any element with a label for it. for example if we want to set the label for the name textfield we will set like that;

$this->name->setLabel("Name of Text");

for password ;
$this->password->setLabel("Enter your password");
and so on.

Validation in Zend

A form element can be validated either by passing the validate  value or by passing Zend_validate_* object. like for alphabets validation we can either pass 'alpha' or Zend_validate_alpha to the addValidator method.

adding validation to text field can be like that;
$this->name->addValidator('alpha'); or 
$this->name->addValidator(new Zend_Validate_Alpha);

or if we want to validate the password field only to the alpha-numeric value we can do that as
$this->password->addValidator('alnum');
or 
$this->passworld->addValidator(new Zend_Validate_Alnum);

and when we add something other than alph-numeric to the password field we will be given error saying that this field can only be alph-numeric.


Tuesday, 20 January 2015

Working with forms

Zend Forms;

Zend_Form simplifies form creation and handling in your web application. It performs the following tasks:
  • Element input filtering and validation
  • Element ordering
  • Element and Form rendering, including escaping
  • Element and form grouping
  • Element and form-level configuration
Zend_Form makes use of several Zend Framework components to accomplish its goals, including Zend_ConfigZend_Validate,Zend_FilterZend_Loader_PluginLoader, and optionally Zend_View.
Creating project;
first we have to create project, open command prompt and go to your project directory, that is htdocs if your using XAMPP, or www if you are using WAMP, now type the following command to create a new project
zf create project {project name}
zf create project helloworld
 and this will create a default zend project for you, we have made some changes to the default project but that ok it go along. so far our project look like this


CREATING ZEND FORM
with the command line interface, it is really easy to create forms, just enter the command and zend will create form with necessary directory for you. 
to create form, go to your project directory in the command prompt. now create form by typing the following command.
zf create form {name of the file form}

zf create form myForm

and zend will create application/form/myForm.php file for us, having class name that is extending from the Zend_Form. 
the following code is pre-written in the file.


<?php
class Application_Form_MyForm extends Zend_Form
{
    public function init()
    {
        /* Form Elements & Other Definitions Here ... */
    }
}
now we have the form file created. next we will add some element to the file. it is actually really easy, but the first we have to set the forms action and method attributes. here is the code;
public function init()
    {
        $this->setAction('index/user')         //set the attribute action = "index/user"
              ->setMethod('post'); //set the attribute method="post"
    }
the output of this form is something like that;

<form enctype="application/x-www-form-urlencoded" action="index/user" method="post">
<dl class="zend_form"></dl>
</form>

now we have set our action and methods, lets add some elements to the form.
adding element is easy, 
first we create a variable $name and assign a text element to it than we set the label of the field and set required to true, like that;

       $this->name = new Zend_Form_Element_Text('username');
       $this->name->setLabel('User Name')
         ->setRequired(true);

than we add a new email field and set it label and required attributes.

       $this->email = new Zend_Form_Element_Text('email');
       $this->email->setLabel('Email Addr.')
          ->setRequired(true);

last we add a submit button. 


       $this->submit = new Zend_Form_Element_Submit('Submit');

add this code inside the init() method of the myform.php file. 
first basic form is created. now we have to add some validation to the form field, just like the setlabel() and setRequired() method. 
when an element is created by calling the new Zend_form_Element_Text() method. it creates the html for it. now we call other method to add functionality to the field. 
first we set the label by calling setlable() method of the Zend_form. this will add the label to the field. 
next we call a new method called setRequired() method that will set a class called required , and when we submit the form with empty field this class will show us the message that this field is required and the form will be considered as invalid. 

Thursday, 15 January 2015

Insert,Delete : DbTable

INSERTING DATA;
Inserting data to the table is very easy. We will create a function called insertData() in the User.php
that will accept an array variable. in that array is the form data. we will further use this form data and insert it into the table using simple insert() method.

here is the code;

public function insertData($data){
    $array = array(
    'firstname' => $data['firstName'],
    'lastname'  => $data['lastName'],
    'email'     => $data['email']  
    );
    $this->insert($array);
    }

here in this function we created an array called $array , set the form data to the firstname, lastname and email. than using simple insert function we called the insert() method and pass it the array. This will add the form data to the table.

Now the question is where is the data coming from? It is actually the form data that we created in the
Zend Form Tutorial. that is submitted to the indexController's IndexAction()
 now we have made some changes to the indexAction() that are;

 public function indexAction()
    {
    if (isset($_POST) && !empty($_POST['firstName'])) {
    $data = $_POST;


    $user = new Application_Model_DbTable_Users();
    $user->insertData($data);
    $this->redirect('index/user');
    }
    else {
    $this->redirect('form/index');
    }
    }

Here we pass the $data variable , that contain the form data to the insertData() method of the user.php file.

when the form is submitted, the data is inserted to the table and we are redirected to the index/user page.

DELETING DATA
Deleting data is also realy easy, we will call the delete() method and pass an id value to it. it will delete the value from the database table.

here is the code of deleteData() function in user.php;

public function deleteData($id){
    $where = $this->getAdapter()->quoteInto('id = ?',$id);
    $this->delete($where);

    }

this function get a parameter from the controller called $id, that is the id of the row of table. where clause matches the id with that in table and delete it form the table.
we have also make some changes to the View file user.phtml,
that looks like that now;

<?php foreach ($this->results as $item):?>
<h1><?php echo $item['firstname'];?></h1>
<h3><?php echo $item['lastname'];?></h3>
<span><?php echo $item['email'];?></span><br/><br/>
<a href="<?php echo $this->baseUrl();?>/index/delete/<?php echo $item['id'];?>">delete</a>

<?php endforeach;?>

a link called delete with every item of the table, when we click on delete link, it is forwarded to the delete action of the indexController.php and from where it called the deleteData() function of the user.php and the item is deleted.
here is the deleteAction() code;

public function deleteAction(){
    $data = $this->_getParam('id');
    $user = new Application_Model_DbTable_Users();
    $user->deleteData($data);
    $this->redirect('index/user');

    }

but there is one problem in the route of the project. to make changes to the url we need to do some changes to the index.php file so that we can get the data form the url.
go to your index.php file  and add these lines at the bottom;


$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->addRoute(
'delete',
new Zend_Controller_Router_Route('/index/delete/:id',array('controller'=>'index','action'=>'delete'))
);

now open project in browser and go the index/user  now click the delete link
the item will be deleted and you will be redirected to this page again.
yes you can add a confirmation message if you want, and thats all.


Wednesday, 14 January 2015

Models in Zend

Now that we have created our helloworld database. lets have some fun with it

models

Model is the data layer of the zend framework. it is use to deal with database. all the data logic will go in the model. so as we have users table in our database, We will create a model with the similar name in the model directory of the project.
open your command prompt, go to your project directory and type
zf create db-table {name of  db-table object } {name of actual table}
zf create db-table users users

its actually a dbTable object that we created, here we provide the name of the table and that the name of the file that we want to create as model for the table.
now our project has new file called Users.php  in the model directory. which look like this;



The file has a class and in the class there is a protected variable name $_name = users;
that is actually the name of the table.
 now lets first select some data from the table by calling the method fetchAll();

here is the code now in the Users.php file;

<?php

class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{

    protected $_name = 'users';
    
    public function getUsers(){
     
    return $this->fetchAll();
    }

}

getUsers() function return values of all the users table. when we call this method from the controller and will get all the data of the users table from the database;

but there is one thing before that 
we will first connect to our database, simply go to your project directory and type;

zf configure db-adapter "adapter=PDO_MYSQL&host=localhost&username=root&password=&dbname=helloworld"



now the application.ini file has been made some changes to. that is

now go to the indexController.php and make some changes to the userAction() to get the table data 

public function userAction()
    {
        $user = new Application_Model_DbTable_Users();
        $results = $user->getUsers();
        $this->view->results = $results;
    }

here we create an object of the DbTable_users object and then call its getUser() method that will fetch all the data contained in the table. than we send the results the data to the view called user.phtml
now lets print the data in the user.phtml
here is the code;

<?php foreach ($this->results as $item):?>
<h1><?php echo $item['firstname'];?></h1>
<h3><?php echo $item['lastname'];?></h3>
<span><?php echo $item['email'];?></span><br/><br/>
<?php endforeach;?>

now to to localhost/helloworld/public/index/user and all the results from the database is shown as ;

next we will see how to insert,udate and delete from the database







Tuesday, 13 January 2015

working with database

to  create database go to browser and type localhost press enter;
you will see page;


now click on phpMyAdmin;
new page is;
here click on database 
than enter your name of the database, mine is helloworld;

click create;
database is created. 
Now its time to create Table in database;

add information about your table columns

your table is created
now insert some data;
click insert ->add some data like i did and click go


 now as you see in your table the  data may be like that;


now lets get data from the database table and have some fun with it using database models

Zend Form part 3: Getting Form data

now we have given the address to the form to where to put the its data. as we click the Submit button the form is posted to the indexAction of the indexController. here is the code to check if the form is submitted or not. if it is submitted than we pass the data to the view index.phtml. 
if the form is not submitted than the redirect code will brought us back to the From page.
Make these changes to the indexController.php;

public function indexAction()
    {
        if (isset($_POST) ) {
              $this->view->data = $_POST;
            }
           else {
          $this->redirect('form/index');
         }

    }

and now get the data at the index.phtml like that;

<h1><?php echo  $this->data['firstName'];?></h1>

<p><?php echo  $this->data['lastName'];?></p>

<h3><?php echo $this->data['email'];?></h3>

now open browser go to localhost/helloworld/public/form/index and add some data to the form. Submit the data and now you will see something like;


Zend Form part 2

Lets see how things work in Zend Forms;
First we Create an object of Zend_Form;

$form = new Zend_Form;

Than we set the Action to where we want to post the form by calling the setAction() method 
and setting the Method to POST.
$form->setAction('/resource/process')
     ->setMethod('post');

Than we create a TEXT field by and set the LABEL to First name
$firstName = new Zend_Form_Element_Text('firstName');

we added some other features to the TextField like it is required and cannot be empty 
        $firstName->setLabel('First name')
                  ->setRequired(true)
                  ->addValidator('NotEmpty');

        $lastName = new Zend_Form_Element_Text('lastName');
        $lastName->setLabel('Last name')
                 ->setRequired(true)
                 ->addValidator('NotEmpty');

here we create an Email Field and set its label to Email Address.
        $email = new Zend_Form_Element_Text('email');
        $email->setLabel('Email address')
the addFilter method convert all the string of the field to lowercase;
              ->addFilter('StringToLower')
setRequired method make sure the field is required
              ->setRequired(true)
addValidator valid the fields to not be empty and has to be like email address.
              ->addValidator('NotEmpty', true)
              ->addValidator('EmailAddress'); 
              
     than we, as usual add a submit button and set its Label to Contact Us.   
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Contact us');
        
We have created a form now we will give all the elements to the $form object.
        $form->addElements(array($firstName, 
            $lastName, $email, $submit));

Monday, 12 January 2015

Zend Form

Zend_Form

Zend_Form simplifies form creation and handling in your web application. It performs the following tasks:
  • Element input filtering and validation
  • Element ordering
  • Element and Form rendering, including escaping
  • Element and form grouping
  • Element and form-level configuration
Zend_Form makes use of several Zend Framework components to accomplish its goals, including Zend_ConfigZend_Validate,Zend_FilterZend_Loader_PluginLoader, and optionally Zend_View.

Creating new controller

go to your project in command prompt and type;

zf create controller {controller name}

in my case I will type as;

zf create controller form

a new controller namely formController.php in the project controller directory and with that a new view folder form with index.phtml is also added to the project by zend.


Now we will go to our view file form/index.phtml and create our form. type the following to create form;
<?php 
$form = new Zend_Form;

$form->setAction('/index/index')
->setMethod('post');

$firstName = new Zend_Form_Element_Text('firstName');
        $firstName->setLabel('First name')
                  ->setRequired(true)
                  ->addValidator('NotEmpty');

        $lastName = new Zend_Form_Element_Text('lastName');
        $lastName->setLabel('Last name')
                 ->setRequired(true)
                 ->addValidator('NotEmpty');
             
        $email = new Zend_Form_Element_Text('email');
        $email->setLabel('Email address')
              ->addFilter('StringToLower')
              ->setRequired(true)
              ->addValidator('NotEmpty', true)
              ->addValidator('EmailAddress'); 
              
        
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setLabel('Contact us');
        
        $form->addElements(array($firstName, 
            $lastName, $email, $submit));
       
         echo $form;
        
now go to you site Url and check







Creating Action and Views in Zend

So far we have been working with the Action and Views that Zend provide as default. now we have to create our own Action and Views. Views are used as pages in the website and Actions in controller contain the logic of the views. .

Creating Action inside helloworld

inside command prompt go to your project directory and create an action by typing the following command

zf create action {name of action} {name of controller}

as we know that actions are inside controllers so it is essential to give the Controller name
I am creating user action inside indexController.php my command will be;

zf create action user index

i don't have to give the full name of the controller because Zend is smart enough to recognize it
now an action is created inside indexController.php namely userAction(). 

Creating view for action

Every views is use as a page in website. So every zend view is a page and the logic of the page is inside the Action. in our case our page is user.phtml and the logic of the page goes inside userAction(). now we have to create view for the action. where we can display the data of the action.
To create view just type;

zf create view {name of the controller that contain Action} {name of the action}

in my case i will type;

zf create view index user

now the project have some changes in it;



now we can add code to our views and action. and than access the page inside browser.
let pass an array from userAction() to user.phmtl
first open your indexController.php and inside userAction() type an array like;


and than chage the user.phtml to access the array data as;


now to access our page we have to make some changes to the url 
in Zend we access the action of the controller in the url

projectname/public/{name of controller}/{name of action}

in default case it is;

helloworld/public/index/index

meaning the indexController and indexAction
now as we are Accessing the indexController and userAction we will type as our url as;

helloworld/public/index/user

and long behold this is now a new page
now let make some changes to the layout file so that we can access our page from a link
open layout.phtml and make the following changes


we have made these changes so when we click on the HOME we are taken to index/index 
and when we click on SERVICES  we go to index/user

try this at home

Sunday, 11 January 2015

Enabling Layout in Zend

Layout in zend
Now that we have created our basic application. Next is to create a layout file. In zend it is very easy through command line. Just go to your command prompt. Than to your project directory and type the following;
Zf enable layout
Zend will enable your layout by adding a folder named layout in the application folder with subfolder scripts and layout.phtml file in it.


Now all you have to do is to create your layout.
I have attached files with the tutorial here;


 just download these two files and replace the layout.phtml file with the one in the layout/scripts/layout.phtml file.
Than add the css and images folder into public directory. That’s it, your layout is done so far. Your project should look like this;

Now open the project in your browser, and it should be like this;


Congratulations you have created  the layout for your project.

Quick start with Zend part 1

Zend : Quick start 

Now that we have basic understanding of how zend work. Lets have a quick start with Zend by creating Zend helloworld application.
go to command prompt in windows  and go to your project directory
that is xampp/htdocs/ if you are using Xampp and c:/wamp/www/ if you are using Wamp
create project by typing 
zf create project helloworld
zend will create all the necessary files and folder for your project which look like this;
now go to browser and type the address
localhost/helloworld/public/
you will see the default page of that zend created for you;
Open your project in your favourite text editor, I am using Zend Studio (http://www.zend.com/en/products/studio)
When we first open our project in the browser we see a default page, thats what zend has created for us we have to remove this and add our own code. To do this go to your project helloworld/application/views/scripts/index/index.phtml 
open index.phtml  in the editor and remove all the code that it contain. than type the following code


now open your browser and type localhost/helloworld/public/ you will see;

Congratulations you have your first changes to the view;
now lets go the Controller and have some changes in it. as we kow that Controller is where the logic of the whole program goes. Every controller has actions and every action is some how related to the view. for example controller/indexController.php has an Action called indexAction()  that is related to the view index/index.phtml.  if we have another action in indexController named userAction() our view will be also called user.phtml. 
now lets pass some values from indexAction()  to index.phtml. 
go to indexAction() in indexController.php and type the following 

now we have assign some values to the variables and pass them to the views. Next we access them in the view and print them as we want. So go to index.phtml  and type the following;


now in browser localhost/helloworld/public you will see;

there is no change is the output but this time we pass values from controller to the view. 
the values were stored in two variables and than passed into the view. there we print the values.