Store
Community Documentation

v3 Knowledgebase

How to process a form (CRUD operation with phpFox)

Hi There,

this is my first article on how to start develop with phpFox.

I have intention to create a few basic articles on how to develop with phpFox.

First of all you should read this article:
http://www.phpfox.com/kb/article/144/creating-your-first-add-on/

In this article I will talk about how to process a form and save value on database, so you can learn how to create, read, update and delete from database (CRUD - Create, Read, Update and Delete). Also you can learn how to manage $_POST and $_GET array of PHP.

You always work with almost three files, that are Model, View and Controller.

The Model files are called Service on phpFox (see here: http://www.phpfox.com/kb/article/144/creating-your-first-add-on/creating-a-service/)

The View files are called Template on phpFox.

And the Controller files are called Controller on phpFox.

For process a form create a file into your Template folder how explained on the article "Creating your first addon".

First of all we have 2 table (table1 and table2), the first table have this 3 columns:

1. mytable_id (int incremental that is the ID of the table)
2. select_id (foreign key of the second table)
3. textarea (text field that will be a textarea tag)

The second table (table2) is used for filling the html select tag and it has the following columns:

1. select_id (int key incremental is the ID of the table and foreign key of the first table)
2. select_value (varchar is the value of select)

Second, our addon is called "myaddon" and the view is called "form"

In this article we use the following code into View file:

PHP:
<!-- action value creates in automatic the link http://yoursite.com/myaddon/form or http://yoursite.com/index.php?do=myaddon/form IMPORTANT: change url "mylink" to url "link" in action. If I add this on article, phpFox convert this to http://phpfox.com/myaddon/form
-->
<
form method="post" action="{url mylink='myaddon.form'}">


 <!-- 
you can use the already existing class "table" of phpFox -->
  <
div class="table">
 <!-- 
you can use the already existing class "table_left" of phpFox for label -->
      <
div class="table_left">
        
Select:
        </
div>
<!-- 
you can use the already exist class "table_right" of phpFox for field -->
        <
div class="table_right"
    
            <
select name="val[select_id]" id="select">
                <
option value="">Make your choice:</option>
        {foreach 
from=$aSelects key=iKey item=aSelect} <!-- here we create a loop that renders the select with id and value -->
                <
option value="{$aSelect.select_id}"{if $aArrayForEdit.select_id == $aSelect.select_idselected{/if}> <!-- $aArrayForEdit is array if you edit the recordThis is empty if you add a new one -->
          {
$aSelect.select_value} <!-- $aSelect.select_value return the value of fieldalso $aSelect.select_id return the ID of row -->
        </
option>
        {/foreach} <!-- 
end foreach -->
            </
select>
      
        </
div>

        <
div class="clear"></div>

        <
div class="table_left">
            
Textarea:
        </
div>
        <
div class="table_right">
 <!-- 
$aArrayForEdit.textarea return the value of textare field if we edit rowotherwise this will be empty -->
        <
textarea name="val[textarea]" id="textarea" rows="8" cols="50">{$aArrayForEdit.textarea}</textarea>
        </
div>

        <
div class="clear"></div>
    
  </
div>

  <
div class="table_clear">
    {if 
$isEdit == 1}  <!-- check if we edit a record or add a new one-->
        <
input type="submit" value="Update" class="button" name="val[update]" />
<!-- if 
we edit a recordthen we should add a hidden field with ID of the row for processing a correct row -->
        <
input type="hidden" value="{$aArrayForEdit.mytable_id}name="val[mytable_id]" />   
    {else}
 <!-- if 
we add a new row then it needs only a submit buttonNOTEthe name of submit buttom changesso we can know which operation we are doing on the controller -->
        <
input type="submit" value="Add" class="button" name="val[add]" /> 
    {/if}
  </
div>

</
form


Now we can create the Model file:

PHP:
<?php

defined
('PHPFOX') or exit('NO DICE!');

class 
Myaddon_Service_Myaddon extends Phpfox_Service
{

    public function 
__construct(){}

    
// get value from table2, that will pull a select tag
    
public function getSelect(){

       return 
Phpfox::getLib('database')->select("t2.*")
            ->
from(Phpfox::getT('table2'), 't2')
            ->
where($where)
            ->
order('fc.ordering')
            ->
execute('getRows');

    }

    
// get a row for edit it
    
public function getForEdit($id){

       return 
Phpfox::getLib('database')->select("t1.*")
            ->
from(Phpfox::getT('table1'), 't1')
            ->
where('t1.table_id = '.$id// get row with requested ID
            
->order('t1.table_id')
            ->
execute('getRow');

    }

    
// this is an edit method that requires $aVal array
    
public function edit($aVal){
    
        return 
Phpfox::getLib('database')->update// calls the class Database
          
Phpfox::getT('table1'), // return table name with correct prefix
          
array( // new data to submit
            
'select_id'=>$aVal['select_id'],
            
'textarea'=>$aVal['textarea']
          ),
        
'table_id='.$aVal['faq_id']);

    }

    
// this is an add method that requires $aVal array
    
public function add($aVal){
    
        return 
Phpfox::getLib('database')->insert(
          
Phpfox::getT('table1'),
          array(
            
'select_id'=>$aVal['select_id'],
            
'textarea'=>$aVal['textarea']
          )
        );

    }

}

?>


And that's our Controller file:

PHP:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

class 
Myaddon_Component_Controller_Form extends Phpfox_Component
{

    public function 
process()
    {

        
// check if exists on the get the key "edit" which is the ID of the table (hidden field)
        
if (($editID $this->request()->getInt('edit')))  $isEdit 1// getInt returns int, and values. The url is: "edit_2"
        
else $isEdit 0;
        
// this line of code assigns to the template the var $isEdit for checking if we got edit or add a new one
        
$this->template()->assign('isEdit'$isEdit);

        
// prepares the array for edit, if we don't do this, it could be a warning if we try to use this array without instancing it
        
$aArrayForEdit = array(
            
'mytable_id'=>'',
            
'select_id'=>'',
            
'textarea'=>''
        
);

        
// checks if it is an edit row
        
if($isEdit==1){
        
            
$aArrayForEdit Phpfox::getService('myaddon')->getForEdit($editID); // get data for update
            
        
}

        
// assigns to the template the array if we edit row
        
$this->template()->assign('aArrayForEdit'$aArrayForEdit);
        
        
// gets a select value from the second table and assigns it to the template with one line of code, pretty cool
        
$this->template()->assign('aSelects'Phpfox::getService('myaddon')->getSelect());

        
// that's most important part, we go to check if the form is submitted
        
if (($aVal $this->request()->getArray('val'))) // getArray() method of request class returns all values from form
        
{
        
          
// NOTE: You can add here the validation of $aVal before submitting
        
          
if(isset($aVal['add']) && !empty($aVal['add'])) // checks if the add new button was clicked
          

          
            if (
Phpfox::getService('myaddon')->add($aVal)) // adds a new record
            
{
            
                
$this->url()->send('myaddon.addedwithsuccess'null'Added with success'); // if is added we can use the class URL for go to "addedwithsuccess" view and show message "Added with success"
            
            
}
            
          } elseif(isset(
$aVal['update']) && !empty($aVal['update'])) // checks if the update button was clicked
          


            if (
Phpfox::getService('faq')->edit($aVal)) // updates the record
            
{
            
                
$this->url()->send('myaddon.updatewithsuccess'null'Edited with success'); // the row is updated with success
            
            
}
            
          } 
          
        } 
        
    }

}

?>


You should read the comments of the codes to see how it works.

This is the basic work of CRUD and form submit.

You can also add more code for getting it more secure, like validation.

I hope you like this first tutorial.

If yes, please rate it and I will create more.

If you have question, use comment below.

Good Coding!

Download full code: Codes.zip