XF 2.1 [SOLVED] Create select menu from table data and show in a form

asprin

Active member
I've an entity defined as follows:
PHP:
public static function getStructure(Structure $structure)
{
    $structure->table = 'xf_fc_categories';
    $structure->shortName = 'FC:Categories';
    $structure->primaryKey = 'id_category';
    $structure->columns = [
        'id_category' => ['type' => self::INT, 'required' => true],
        'category_title'  =>  ['type' => self::STR , 'required' => true]
    ];
    $structure->getters = [];
    $structure->relations = [];

    return $structure;
}

It contains data as follows:
1580632721402.png

Is there a way I can pull this data and create a select from it as part of a form that I will show on a page?


I'm aware that to render a select, I'll have to use the following format:
HTML:
<xf:select>   
    <xf:option value="1">
        orange
    </xf:option>
    <xf:option value="2">
        apple
    </xf:option>
    <xf:option value="3">
        banana
    </xf:option>   
</xf:select>

But just not sure how to grab data from database and use it in the above format.
 
Last edited:
Ahem! Figured it out. I don't know why but I tend to find the solution after posting a thread here 🤦‍♂️

For reference purposes, first need to create a repository inside the addon's Repository folder
PHP:
class Categories extends Repository
{
    /**
     * @return Finder
     */
    public function fetchAllCategories()
    {

        $finder = $this->finder('FC:Categories');
        $finder
            ->setDefaultOrder('id_category', 'ASC');

        return $finder;
    }
}
Then use that repo in the controller function and pass that value to view
PHP:
$cat_repo = $this->repository('FC:Categories');
$cat_finder = $cat_repo->fetchAllCategories();
$categories = $cat_finder->fetch();
$viewParams = [           
   'categories' => $categories
];

And finally inside the view
HTML:
<xf:select name="some_name">
    <xf:option>Select One</xf:option>
    <xf:foreach loop="$categories" key="$id" value="$obj">
        <xf:option value="{$id}">{$obj.category_title}</xf:option>
    </xf:foreach>
</xf:select>
 
Top Bottom