phpjoomlajform

How to preset JFormField values?


I'm working on a Joomla module that have a form with a custom field that extends the JFormField class. I'd like use this form to display a database record and let the user to modify the saved data. I created the custom field to display a list based on an external database table. Everything works fine, except that I'm unable to preset the value of custom field to display the value in the database. I tried two approaches, but none of them seem to work:

1:

$form->setFieldAttribute('orderstatus', 'default', '1', $group = null);

2:

$form->setValue('orderstatus','main','1');

Any recommendations? Thanks a lot!


mod_gngtourdetails.php:

$filepath = dirname(__FILE__) . '/tourDetailsForm.xml'; 
$form=new JForm('mod_gngtourdetails');
$form->loadFile($filepath);
ModGngTourDetailsHelper::preFillForm($form, $tourDetails);

tourDetailsForm.xml

<form>
    <fields name="main">
        <fieldset name="basic" addfieldpath="/modules/mod_gngtourdetails/models/fields">
            <field
                name="ID"
                type="text"
                label="ID"
                description="ID"
                size="10"
                maxlenght="10"
            />
            <field
                name="orderstatus"
                type="orderstatus"
                label="Order Status"
                description="Order Status"

            />

orderstatus.php

class JFormFieldOrderStatus extends JFormField {

    protected $type = 'orderstatus';

    function getDB() {
        
        ...
        return $db;
    }


    public function getInput() {
            
        
        $db = JFormFieldOrderStatus::getDB(); 
                
        $query = $db->getQuery(true);
        $query->select($db->qn('ORDER_STATUS.NAME','NAME'));
        $query->select($db->qn('ORDER_STATUS.ID','ID'));
        $query->from($db->qn('ORDER_STATUS'));
        $query->order('ORDER_STATUS.NAME ASC');

        $rows = $db->setQuery($query)->loadObjectlist();
                
        $result = '<select id="'.$this->id.'" name="'.$this->name.'">';
        
        foreach($rows as $row){
            $result .=  '<option value="' . $row->ID .'" >' . $row->NAME . '</option>'; 
        }
        $result .= '</select>';
        
        return $result;
        
    }
}

Solution

  • The first method should work, but should be

    $form->setFieldAttribute('orderstatus', 'default', '1', 'main');
    

    Another thing, is that you should rather extend JFormFieldList, and in particular the getOptions() function.