Search code examples
phpmysqldatabasemariadbnette

Unable to insert the information retrieved from a database inside a form


I am new to Nette and php frameworks in general. I am trying to create a form with a selection menu that takes the list of selectable options from a columns inside the database.

<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette\Application\UI;

class HomepagePresenter extends UI\Presenter
{


     /** @var Nette\Database\Context */

     private $database;

     public function __construct(\Nette\Database\Context $database)
     {
         $this->database = $database;
     }

    protected function createComponentCalculationForm(): UI\Form
    {
        $result=$this->database->query('SELECT supp_name FROM suppliers');
        foreach($result as $supplier){
            $supplierList[]=$supplier;
        }

        $form = new UI\Form;
        $form->addSelect('supplier', 'Dodavatel:',$supplierList);
        $form->addText('quantity', 'Ks')
             ->setRequired()
             ->addRule($form::INTEGER,"Hodnota musí být číslo" )
             ->addRule($form::MIN,'Číslo musí být kladné!',0);
        $form->addText('price', 'Kč')
             ->setRequired()
             ->addRule($form::INTEGER,"Hodnota musí být číslo" )
             ->addRule($form::MIN,'Číslo musí být kladné!',0);
        $form->addButton('calculate', 'Spočítat')
             ->setHtmlAttribute('onclick', 'calculatePrice()');
        $form->addTextArea('result');
        return $form;
    }

}

I'd like the $form select menu to include the list of suppliers


Solution

  • $supplier variables will contain Nette\Database\Row, which you store into the $supplierList array. Form::addSelect expects array, where the values are things that can be stringified. Since Row does not like to be stringified, you need to add to the list something that does. Extracting the column should work:

            $result = $this->database->query('SELECT supp_name FROM suppliers');
            foreach($result as $supplier){
                $supplierList[] = $supplier['supp_name'];
            }