3 - Add an item

Now you may want to add an item to the database

The "new" button in cars list page will redirect you to the edit page.

administrator / components / com_dealer / car / view.html.php


<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');


/**
 * View file
 */
class DealerViewCar extends JViewLegacy
{

    
/**
     * The JForm object
     *
     * @var  JForm
     */
    
protected $form;

    
/**
     * The active item
     *
     * @var  object
     */
    
protected $item;

    
/**
     * The model state
     *
     * @var  object
     */
    
protected $state;

    public function 
display($tpl null
    {
        
$form null;
        
$this->item  $this->get('Item');        

        try
        {
            
$form $this->get('Form');
        }
        catch (
Exception $e)
        {
            
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');

            return 
false;
        }

        
// Bind the form to the data.
        
if ($form && $this->item)
        {
            
$form->bind($this->item);
        }

        
$this->form = &$form;

        
// trigger plugin
        
$this->prms = new stdClass();
        
JPluginHelper::importPluginBp::getComponent() );
        
$dispatcher JEventDispatcher::getInstance();
        
$results $dispatcher->trigger'on'.ucfirst(Bp::getComponent()).ucfirst(Bp::getView()).'DataPrepare'
                                            
, array( &$this->form, &$this->prms ) );
        
        
// buttons and page title
        
BpForm::admAddItemButtons(Bp::get('my_key_id'0));

        
parent::display($tpl);
        
    }

}
// pure php no tag

As you can easily guess, at this point, you can copy and paste the whole script for every item view in your component, changing the class's name and "my_key_id" accordingly with the ID key of your database table.

The method appends the (most commonly used) buttons:

  • apply
  • save
  • save2new
  • cancel

If you are thinking that you can easily disable some button(s) passing to the method an array of instructions... you already learned how to use the BPLibrary!

As you can see the learning curve is really superfast!

Alter the form with a plugin

Sometimes you may want to use only one xml form file to handle different template pages. Say you have an xml form with 4 different fieldsets, for the sake of clarity we will call them set1, set2, set3, set4.

You can easily manage the fieldsets using the method removeFieldset() of the class BpForm. As the library is available at the framework level, you can use it in every moment.

For the example of the car dealer, give it a try using a plugin with an 'onDealerCarDataPrepare' event and remove the fieldset(s) using BpForm::removeFieldset( $form, 'fieldsetName') for every fieldset you want to remove.
To remove 'set1' and 'set3':

$form = BpForm::removeFieldset($form, 'set1');

$form = BpForm::removeFieldset($form, 'set3');