Exemplo n.º 1
0
 protected function save()
 {
     $this->model->values($this->request->post());
     // clean null values
     foreach ($this->model->table_columns() as $field => $values) {
         $is_boolean = Arr::get($values, 'data_type') === 'tinyint' and Arr::get($values, 'display') == 1;
         $is_nullable = Arr::get($values, 'is_nullable');
         $has_value = (bool) $this->model->{$field} and $this->model->{$field} !== NULL;
         if ($is_nullable and !$is_boolean and !$has_value) {
             $this->model->{$field} = NULL;
         }
     }
     try {
         if (isset($_FILES)) {
             foreach ($_FILES as $name => $file) {
                 if (Upload::not_empty($file)) {
                     $filename = uniqid() . '_' . $file['name'];
                     $filename = preg_replace('/\\s+/u', '_', $filename);
                     $dir = DOCROOT . 'public' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . strtolower($this->model_name);
                     create_dir($dir);
                     Upload::save($file, $filename, $dir);
                     $this->model->{$name} = $filename;
                 }
             }
         }
         if ($this->parent_id) {
             $this->model->{$this->parent . '_id'} = $this->parent_id;
         }
         $this->has_many = Arr::merge($this->has_many, $this->model->has_many());
         $this->save_before();
         $this->model->save();
         $this->save_after();
         // ignore external relations
         $has_many_through = array_filter($this->has_many, function ($item) {
             return strpos(Arr::get($item, 'through'), $this->model->table_name() . '_') === 0;
         });
         // add has many
         foreach ($has_many_through as $name => $values) {
             $ids = $this->request->post($name);
             $this->model->remove($name);
             if (!$ids) {
                 continue;
             }
             $this->model->add($name, $ids);
         }
         $this->flush();
         if ($this->request->is_ajax()) {
             $this->response->json($this->model->all_as_array());
             return;
         }
         Session::instance()->set('success', 'Registro salvo com sucesso!');
         if ($this->redirect === NULL) {
             HTTP::redirect($this->url());
         } else {
             HTTP::redirect($this->redirect);
         }
     } catch (ORM_Validation_Exception $e) {
         $errors = $e->errors('models');
         if (!$errors) {
             $errors = array($e->getMessage());
         }
         View::set_global('errors', $errors);
         if ($this->request->is_ajax()) {
             $this->response->json(array('errors' => $errors));
         }
     }
 }