0

Is there a way to modify the template data for Twig/Slim via the Response object? Otherwise, what is the recommended strategy to load and populate forms from a failed form submit?

class Item extends Model {} // eloquent model
class ItemOption extends Model {} // eloquent model

class controller
{
    // this route is for loading the form and pre-populating it for editing
    public function getItemForEditing($request, $response)
    {
        $item = Item::find($request->getAttribute('id'));
        $options = ItemOption::all(); // this is to populate HTML select input

        return $this->view->render($response, 'edit-item.twig', [
            form => $item.toArray(),
            options => $options.toArray(),
        ]);
    }

    // this route is when edit form is submitted
    public function postItemForEditing($request, $response)
    {   
        $errors = $this->validate(...);
        if(!empty($errors))
        {
            // by reusing this route to get the response, 
            // I automatically take care of all the template data necessary
            // to be passed to the twig view
            $response = $this->getItemForEditing($request, $response);

            // this method does not exists, but if it does,
            // then I can just update/append any additional data from here
            $response->data([
                form => $request->getParams(), // replace DB values with latest inputs
                error => $errors,
            ]);

            // finally return the response
            return $response;
        }
        else
        {
            // update Item in database
            ...
        }
    }
}

// inside edit-item.twig template
<input type="text" value="{{ form.price }}">
<select>
    {% for option in options %}
    <option value="{{option.id}}" {% if option.id == form.option_id %}selected{% endif %}>{{option.name}}</select>
    {% endfor %}
</select>
Jake
  • 11,273
  • 21
  • 90
  • 147
  • 1
    Why not just pass the errors array towards `getItemForEditting` and check from there? (Thats why I do though) – DarkBee Oct 26 '17 at 19:40
  • @DarkBee sorry, I don't get what you mean.Are you saying `$this->getItemForEditing($request, $response, $error)`? Why don't you write an answer with code example? – Jake Oct 27 '17 at 03:11

0 Answers0