Magento Developper’s Guide (Lesson 5) – The Model, collections and forms

12 octobre 2011

This tutorial is the 5th of many , if you do not have already read them from the start, i suggest you to start with the summary of this series.

We have in the previous tutorials creates a module with a controller, a block and its template and a connection to the database. We will now see how to go further with the database and how to better interact with magento.

model, collections, forms …

As we saw earlier to retrieve data from your database, you have to use the getModel , which takes as parameters the type of object, in the previous tutorial we defined an object type test/test in our model.

So we will get this model by:

       Mage::getModel('test/test');

With this model you can store messages and nicknames and you can retrieve an object in your database. If I want to get for example the « test » object with the identifier 2, you will do:

      Mage::getModel('test/test')->load('2');

Now we want to retrieve all objects of this type that have been registered in our database. To do this we will use what is called a collection we will get through the method getCollection from our model.

      $macollection =  Mage::getModel('test/test')->getCollection();

With this collection, we can make operation on our database such as:

     $macollection =  Mage::getModel('test/test')->getCollection();
     //sorted by ID
     $macollection->setOrder('id_pfay_test','asc');
     //only select those withe the phone number 03 20 58 74 89
     $macollection->addFilter('telephone', '0320587489');
 

Now, what would you say if you put your module in a form to add phone numbers directly from the frontend and it sorts the entries by user name when viewing? anyone? Ok here we go!

1 – Sort data when viewing

We have seen in the previous tutorial, your contact list is displayed in your block

So open Monbloc.php located in app/code/local/Pfay/Test/Block and change this line:

    $collection = Mage::getModel('test/test')
                        ->getCollection()
                        ->setOrder('id_pfay_test','asc');

You notice it’s done in this line of code (it’s crazy it’s really good ^ ^).

2 – Add the Form

Edit the Template afficher.phtml located in \app\design\frontend\pfay\theme\template\test\ as this:

<form action="<?php echo Mage::getUrl('test/index/save') ?>" method="post">
  <fieldset>
    <ul>
     <li>
       <label for="nom">Nom</label>
       <input type="text" id="nom" name="nom" />
     </li>
     <li>
         <label for="prenom">Prenom</label>
         <input type="text" id="prenom" name="prenom" />
     </li>
     <li>
        <label for="nom">Telephone</label>
        <input type="text" id="telephone" name="telephone" />
    </li>
     <li>
        <input type="submit" value="Save" />
    </li>
  </ul>
 </fieldset>
</form>
<?php
   echo $this->methodblock();
 ?>

Explanation: This is a form, it send the informations to the method save of your controller IndexController of your module Test . The url will be found using the method getUrl.

Now, what happen when we send the form? Open the controller IndexController of your module Test (/app/code/local/Pfay/test/controllers /) and add the following method:

 public function saveAction()
 {
    //on recuperes les données envoyées en POST
    $nom = ''.$this->getRequest()->getPost('nom');
    $prenom = ''.$this->getRequest()->getPost('prenom');
    $telephone = ''.$this->getRequest()->getPost('telephone');
    //on verifie que les champs ne sont pas vide
    if(isset($nom)&&($nom!='') && isset($prenom)&&($prenom!='')
                               && isset($telephone)&&($telephone!='') )
   {
      //on cree notre objet et on l'enregistre en base
      $contact = Mage::getModel('test/test');
      $contact->setData('nom', $nom);
      $contact->setData('prenom', $prenom);
      $contact->setData('telephone', $telephone);
      $contact->save();
   }
   //on redirige l’utilisateur vers la méthode index du controller indexController
   //de notre module <strong>test</strong>
   $this->_redirect('test/index/index');
}

To understand what i’ve made, read the comments in the code, it retrieves information on the form and saves them on base and then redirects to the index method.

Note that this piece of code that I put in the save method, we could have put it in the method of the block in order to record information in your list no matter where on your website you insert the block … it works well.

Your homework: again this tutorial, try saving your form data, practice blocks. .., that’s how we get there.

end of this tutorial Congratulations you have reached the end of this tutorial. Leave a message comment, It’s always nice and i love to talk with you guys ;)

find the summary of this tutorial

You should read this too :
  • No Related Post
Tike # 5 décembre, 2011

Cool! That’s a celver way of looking at it!

# 15 décembre, 2011 Lalgamba

Guys, if you are a beginner and want to create your own module, go through this tutorial. This is a gr8 one. This tutorial is awesome.

Sreedevi # 27 décembre, 2011

Hi all, this tutorial is a nice one. It helped me a lot!

# 10 avril, 2012 Geoff

Great tutorial. Onwards

roshan # 19 mai, 2012

Another greate tutorial

# 30 mai, 2012 shailendra

man can u write the comments and other stuff also in english .i am having a problem in understanding few things

marius # 29 août, 2012

Thank you man! Great documentation!!

# 22 octobre, 2012 Vijay

yup, this is a good tutorial for beginners. All the best Pierrefay :)

Mizandeveloper # 17 novembre, 2012

Great Tutorial.Thx a lot.keep it up….

# 18 janvier, 2013 mrgun

thank you ! good job

ouafae # 25 février, 2013

Hi,
Thanks a lot for your tutorials, they’re really helpful.

# 5 juin, 2013 nikunj vadariya

Thanks boss :)

Jose Manuel Orts # 23 août, 2013

Thank you very much Pierre, great job!!

# 6 septembre, 2013 Rashmi

Just Amazing..!!

Fabi # 11 septembre, 2013

Nice tutorial. But as always just a tutorial for complete new forms, blocks, …
I am looking for a tutorial to extend, edit and save existing forms in the backend :(

# 30 octobre, 2013 Quyết

Thanks you so much. That’s good for me.

Rebin N Shaju # 18 novembre, 2013

Cool ..! thk u so much..

# 14 janvier, 2014 Bhupen Singh Panwar

Superb..

Vous aussi donnez votre avis
(requis)



Expert magento sur Lille - Pierre FAY