Form default values with Multiplier

sztanp
Member | 9
+
0
-

Hi there,

Is there a built-in way to use setDefaults($arr) with a Form inside a Multiplier ?

I do this :

protected function createComponentProductForm()
   {
       return new Multiplier(function ($productId) {

           $form = new Nette\Application\UI\Form;

           $form->addText('name', 'nom du produit:')
               ->setRequired('Entrer un nom pour le produit.');

           $form->addText('details', 'description du produit:')
               ->setRequired('Entrer une description pour le produit.');

           $form->addText('baseprice', 'prix de base:')
               ->setRequired('Entrer un prix de base pour le produit.');
           $form->addHidden('productId', $productId);
           $form->addSubmit('send', 'Modifier');
           $form->setDefaults($this->resultSet[$productId]); // this is the tricky part
           return $form;
       });
   }

   public function actionList() {
       $products=$this->productManager->getProduct(); //with no parameter = get all products
       $this->template->products=$products;
       while($product=$products->fetch()) {
            $this->resultSet[$product["id"]]=$product; // this is the tricky part
       }
   }

and in the template :

{foreach $products as $product}
    {control productForm-$product->id}
{/foreach}

I'm not sure it's the cleanest way ?

Regards,
Stanislas

Last edited by sztanp (2018-04-15 21:41)

CZechBoY
Member | 3608
+
0
-

I think there is no other way… btw you do not need that hidden field, because you always know the product id from multiplier parameter…

sztanp
Member | 9
+
0
-

Yes I use it, you couldn't see it as I didn't put this part in my excerpt :

...
$form->onSuccess[] = [$this, 'productFormSucceeded'];
...

and

public function productFormSucceeded(Form $form, $values)
    {

        $productId = $values['productId'];

        $this->database->table('products')
                ->where('id',$productId)
                ->update([
                    'name' => $values->name,
                    'details' => $values->details,
                    'baseprice' => $values->baseprice]);

        $this->flashMessage('produit "'.$values->name.'" mis à jour', 'success');
        $this->redirect('this');

    }

But do you think I could get the productId by any other way to validate the form ?…

CZechBoY
Member | 3608
+
0
-
$form->onSuccess[] = function (Form $form, ArrayHash $values) use ($productId) {
    $this->productFormSuceeded($form, $values, $productId);
};

Last edited by CZechBoY (2018-04-16 09:23)