phpjoomlajform

Joomla custom JForm. Generating values with foreach cycle


anyone could tell me why this isn't working ? The mistake is somewhere in foreach cycle.

jimport('joomla.form.formfield');

class JFormFieldCity extends JFormField {

        protected $type = 'city';

        public function getInput() {
        $db = JFactory::getDBO();
        $db->setQuery(
            'SELECT title' .
            ' FROM #__content'
        );
        $title = $db->loadObjectList;

                return '<select id="'.$this->id.'" name="'.$this->name.'">'.
                                           foreach ($title as $titlex)
                       {
                       '<option value="6" >'.$titlex.'</option>'
                       }
                       '</select>';} }

Solution

  • Below is an edited code, this will be helpful if you are creating custom field from xml.Have a try and let me know if it does not work.

         // No direct access to this file
            defined('_JEXEC') or die;
    
            // import the list field type
    
    
       jimport('joomla.form.helper');
        JFormHelper::loadFieldClass('list');
    
    
        class JFormFieldCity extends JFormFieldList
        {
            /**
             * The field type.
    
         *
         * @var     string
         */
        protected $type = 'city';
    
        /**
         * Method to get a list of options for a list input.
         *
         * @return  array       An array of JHtml options.
         */
        protected function getOptions() 
        {
            $db = JFactory::getDBO();
            //$query = new JDatabaseQuery;
            $query = $db->getQuery(true);
            $query->select('id,title');
            $query->from('#__content');         
            $query->order('title'); 
            $db->setQuery((string)$query);
            $messages = $db->loadObjectList();
    
            $options = array();
            if ($messages)
            {
                foreach($messages as $message) 
                {
                    $options[] = JHtml::_('select.option', $message->title, $message->title);
                }
            }
    
            $options = array_merge(parent::getOptions(), $options);     
            return $options;
        }
    }