How do I update form fields with data from database?

(Apsprint) #1

My application is a print job ordering site. I am working with a freshly created app with only two models for testing the particular problem I am having.

The Job model:
id, quantity, ink, stock_id, width, height, press_width, press_height
stock_id is a foreign key to
press_width and press_height refer to the size of the paper which is often larger than the width and height of the job. These are the form fields I want to update when stock_id is selected by dropdown in the job/create form.

The Stock model:
id, name, width, height

What I am trying to do is to have the values for press_width and press_height update based on the width and height values from the stock table based on the the stock_id selected. I have experimented with adding ‘onchange’=>‘javascript_function(selected_stock_id)’ to the stock_id dropdown. I was able to pass the selected stock_id to the javascript function using ‘onchange’ => ‘getWidthHeight(this.value)’. The id did me no good in the function, so I changed it to receive a width and height and change the form fields for press_width and press_height, ‘onchange’ => ‘getWidthHeight(width, height)’ It worked if I passed hard coded values. I created model methods to return the stock width and height, $model->getWidth($stock->id). I was able to get it to sort of work with, ‘onchange’ => ‘getWidthHeight(’.$model->getWidth(2).’,’.$model->getHeight(2).’)’ It pulled the width and height from the database for stock 2 and changed the values like I wanted. It did not work when I replaced 2 with ‘this.value’, the id I need to pass to the model methods.

I don’t know if my approach needs tweaking or if I need a totally different approach.

(smohadjer) #2

You don’t need any javascripting. When your form posts width and height of a specific stock, in your controller you save these values to corresponding row in job table which you find using stock id. Everything you need to get it done is explained in this guide:, in particular pay attention to section “Working with Relational Data” in that article.