public static function update() { self::check_logged_in(); $curruser = self::get_user_logged_in(); if (!$curruser->admin) { Redirect::to('/user/' . $curruser->id, array('warning' => 'Pääsy kielletty ilman ylläpito-oikeutta!')); } $p = $_POST; $poll = new Poll(array('id' => $p['id'], 'name' => $p['name'], 'description' => $p['description'], 'start_time' => $p['start_time'], 'end_time' => $p['end_time'])); // Search the input array for Option model attributes and build an array // out of them: $poll_options = array(); foreach ($p as $key => $value) { $matches = array(); if (preg_match("/^option_name_([0-9]+)\$/", $key, $matches)) { $poll_options[$matches[1]]['id'] = $p['option_' . $matches[1]]; $poll_options[$matches[1]]['name'] = $p[$matches[0]]; $poll_options[$matches[1]]['description'] = $p['option_description_' . $matches[1]]; } else { if (preg_match("/^option_name_new_([0-9]+)\$/", $key, $matches)) { $poll_options[$matches[1]]['name'] = $p[$matches[0]]; $poll_options[$matches[1]]['description'] = $p['option_description_new_' . $matches[1]]; } } } $errors = $poll->errors(); $polloptions = array(); if (count($errors) == 0) { $poll->update(); foreach ($poll_options as $option) { $polloption = new PollOption(array('polls_id' => $poll->id, 'name' => $option['name'], 'description' => $option['description'])); $errors = $polloption->errors(); if (count($errors) == 0) { if (isset($option['id'])) { $polloption->id = $option['id']; $polloption->update(); } else { $polloption->save(); } } else { $polloptions[] = $polloption; } } if (empty($polloptions)) { Redirect::to('/poll/' . $poll->id, array('message' => 'Tallennettiin äänestys ' . $poll->name . '.')); } else { // The poll was saved successfully but options weren't. Edit the poll. $errors[] = 'Tallennettiin äänestys ' . $poll->name . ', mutta äänestyksen vaihtoehtoja ei saatu tallennettua. Tarkista virheet'; View::make('poll/edit.html', array('errors' => $errors, 'poll' => $poll, 'polloptions' => $polloptions)); } } else { // The actual poll wasn't saved. foreach ($poll_options as $option) { $polloption = new PollOption(array('polls_id' => $poll->id, 'name' => $option['name'], 'description' => $option['description'])); if (isset($option['id'])) { $polloption->id = $option['id']; } $optionerrors = $polloption->errors(); if (!empty($optionerrors)) { $errors = array_merge($errors, $optionerrors); } $polloptions[] = $polloption; } View::make('poll/edit.html', array('errors' => $errors, 'poll' => $poll, 'polloptions' => $polloptions)); } }