views:

39

answers:

1

This is a question I had about working with the Kohana framework, though I imagine that this is something that could apply to MVC frameworks in general.

Let's say I have 2 objects/models, an animal object and a farm object, where an animal belongs to a farm, and a farm has many animals. I have a form for creating new animals, and I want to have a drop down to select which farm it belongs to. My question is how best to handle getting the data from the farm table and display it in the form.

Here are a few possible solutions I came up with, but I'm not sure any of them are the best approach. also, I planned on using Kohana's Form helper library, but that only seems to handle HTML rendering of the forms:

  1. Get the data in the AnimalModel, pass it to the controller, which passes it to the form view. However I'm not sure if this should be the AnimalModel's responsibility.
  2. Get the data from the FarmModel. My concern here is that is something has a lot of relations, the controller is going to have to start calling a lot of different controllers.
  3. Store all the data that gets passed to the various form methods in the AnimalModel. This would also involve storing things like classes, which seems like it shouldn't be in the model.
  4. Write some kind of helper Object/Library to store all the form data, and keep it in the Model, or possibly the Controller. Again though, I feel like this would end up with a mixing of display and business logic, which I would like to enjoy.

Another concern I had when designing this is other things that come up with forms, such as validation, and also what to do when I want the form in 'edit' mode, and I need to pre-populate it with data from the Model.

What's the best way to approach writing forms that deal with relations in Kohana/MVC Frameworks?

+1  A: 

Maybe im missing your question but it seems like you're overcomplicating things. Use a Farm model to get a list of all your farms. Use this list to create a select in your form.

<select name="farm">
    <option value="1">Farm 1</option>
    <option value="2">Farm 2</option>
    <option value="3">Farm 3</option>
</select>

Then when you save your animal you have the primary key for the farm it belongs to.

$animal = $_POST;
if ( $animal->validate() ) {
    $animal->save(); //saves all your animal data as well as the farm it belongs to.
}
else {
    // show your view and display the animal data
}

your view could do somethign like this

<label>Animal Name</label><input type="text" value="<?php echo  $animal->getValue('name') ?>">
Galen
I may be overcomplicating things, but also the example I gave was a simple one. What happens when objects have a bunch of other relations?
GSto