How to populate edit form from database

+
0
-

I have a form, to edit values in a database, based on an ID in the url.

How do I get the data related to the URL ID?

If I do this:

<?php
protected function createComponentEditRecipeForm( $id )
?>

Then $id contains “editRecipeForm”
How do I pass the $id to the form?

radekBrno
Member | 61
+
+1
-

You can use action in presenter.

/** @var $id */
private $id;

...

public function actionEdit($id)
{
    $this->id = $id;
}

kevin.waterson@gmail.com wrote:

I have a form, to edit values in a database, based on an ID in the url.

How do I get the data related to the URL ID?

If I do this:

<?php
protected function createComponentEditRecipeForm( $id )
?>

Then $id contains “editRecipeForm”
How do I pass the $id to the form?

Last edited by radekBrno (2020-01-15 10:47)

Toanir
Member | 57
+
0
-

Hi Kevin,

I suggest to separe form creation and population. In simple forms this allows for reuse for creation and editing. You can do that like this:

<?php
class RecipePresenter {

    public function actionCreate() {
        $recipeForm = $this['recipeForm'];
        $recipeForm->onSuccess[] = function($form, $data) use ($id) {
            recipe_creation_magic($id, $data);
        };
    }

    public function actionEdit(int $id) {
        $recipe = recipe_obtaining_magic($id);
        $recipeForm = $this['recipeForm'];
        $recipeForm->setDefaults([
            'name' => $recipe->name,
            'duration' => $recipe->duration,
        ]);
        $recipeForm->onSuccess[] = function($form, $data) use ($id) {
            recipe_updating_magic($id, $data);
        };
    }


    protected fucntion createComponentRecipeForm() {
        $form = new \Nette\Application\Form();
        $form->addText('name', 'Recipe name');
        $form->addSelect('duration', 'Duration', [
            'quickie' => 'Quick recipe (10 to 30 mins)',
            'moderate' => 'Moderate recipe (30 mins to 2 hours)',
            'long' => 'Long recipe (2 hours or longer)',
        ]);

        return $form;
    }
}
+
0
-

Thanks Toanir.
Working on it.