public function setModel($model, $fields = null, $grid_fields = null)
    {
        $model = parent::setModel($model);

        if (!isset($this->entity_name)) {
            if (!isset($model->caption)) {

                // Calculates entity name
                $class = get_class($this->model);
                $class = substr(strrchr($class, '\\') ?: ' '.$class, 1); // strip namespace
                $this->entity_name = str_replace(
                    array('Model_', '_'),
                    array('', ' '),
                    $class
                );
            } else {
                $this->entity_name = $model->caption;
            }
        }

        if (!$this->isEditing()) {
            $this->configureGrid(is_null($grid_fields) ? $fields : $grid_fields);
        }

        if ($this->allow_add) {
            if ($this->configureAdd($fields)) {
                return $model;
            }
        } elseif (isset($this->add_button)) {
            $this->add_button->destroy();
        }

        if ($this->allow_edit) {
            if ($this->configureEdit($fields)) {
                return $model;
            }
        }

        if ($this->allow_del) {
            $this->configureDel();
        }

        return $model;
    }