Multiple Tables Insert From Single Form

Home Forums Zend Framework 2 Multiple Tables Insert From Single Form

This topic contains 0 replies, has 1 voice, and was last updated by  ThisSiteSpams! 2 years, 6 months ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #608

    ThisSiteSpams!
    Participant

    How do I use a single form to update multiple tables? For example building on the Album example (from zf2 website) how would I insert (one or many genres) for a given album (one to many relation between genre and albums)?

    From the example I have added a Genre.php file under the Model Folder (this contains the Input Filter for the Genre table).

    I have updated the Form to include a genre name field and a hidden genre id. This change is then reflected on the view.

    I am having troubles figuring out the controller side. Below is my current controller code for the addAction. Please let me know if I can provide any further information. Thank you for your time and help!

    Matt

    AlbumController:

    public function addAction()
    {
    $form = new AlbumForm();
    $form->get(‘submit’)->setValue(‘Add’);

    $request = $this->getRequest();
    if ($request->isPost()) {

    $album = new Album();

    $form->setInputFilter($album->getInputFilter());
    $form->setData($request->getPost());

    if ($form->isValid()) {

    $album = new Album();
    $genre = new Genre();

    $fields = array(
    ‘album’=>array(‘id’,’title’,’artist’), //assign fields to correct tables
    ‘genre’=>array(‘genre_id’,’id’,’genre’)
    );

    $userData=array();
    $genreData=array();

    foreach(array_keys ($fields) as $type){
    $varName =$type. “data”;
    foreach($fields[$type] as $name){
    $varName[$name]=$form->getValue($name);
    }
    }

    $album->exchangeArray($form->getData());
    $this->getAlbumTable()->saveAlbum($album);

    $genre->exchangeArray($form->getData());
    $this->getGenreTable()->saveGenre($genre);

    // Redirect to list of albums
    return $this->redirect()->toRoute(‘album’);
    }
    }
    return array(‘form’ => $form);
    }

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.