tags:

views:

395

answers:

1

I've got some sample code that I'd like to refactor as I need it to work after a record is saved. It currently works after the record is first rendered (using the afterFilter). What it does is render the view that I want with the layout and saves it to a file.

function afterFilter() {
    parent::afterFilter();
    if($this->params['pass'][0] == 'contact') {
        $surrenderOuput = $this->surrender($this->params['pass'][0]);
        $path = WWW_ROOT . 'cache' . DS . $this->params['pass'][0] . DS . 'index.html';
        $file = new File($path, true);
        $file->write($surrenderOuput);
        $file->close();
    }
}
function surrender($action = null, $layout = null, $file = null) {
 $this->beforeRender();

 $viewClass = $this->view;
 if ($this->view != 'View') {
  if (strpos($viewClass, '.') !== false) {
   list($plugin, $viewClass) = explode('.', $viewClass);
  }
  $viewClass = $viewClass . 'View';
  App::import('View', $this->view);
 }

 $this->Component->beforeRender($this);

 $this->params['models'] = $this->modelNames;

 if (Configure::read() > 2) {
  $this->set('cakeDebug', $this);
 }

 $View =& new $viewClass($this);

 if (!empty($this->modelNames)) {
  $models = array();
  foreach ($this->modelNames as $currentModel) {
   if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
    $models[] = Inflector::underscore($currentModel);
   }
   $isValidModel = (
    isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
    !empty($this->$currentModel->validationErrors)
   );
   if ($isValidModel) {
    $View->validationErrors[Inflector::camelize($currentModel)] =&
     $this->$currentModel->validationErrors;
   }
  }
  $models = array_diff(ClassRegistry::keys(), $models);
  foreach ($models as $currentModel) {
   if (ClassRegistry::isKeySet($currentModel)) {
    $currentObject =& ClassRegistry::getObject($currentModel);
    if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
     $View->validationErrors[Inflector::camelize($currentModel)] =&
      $currentObject->validationErrors;
    }
   }
  }
 }

 $this->autoRender = false;
 $output = $View->render($action, $layout, $file);

 return $output;
}

So I'm basically rendering the view with it's layout, and returning it as output, and saving it to a file. Great. Is there any way to do something similar in a model?

+2  A: 

You may consider setting a member variable in your afterSave() in the model and checking that value in your afterFilter() in your controller.

Kevin
I ended up doing a behavior using the Model::afterSave(). Took a while to figure out how to do so, but using Controller::render() is not the way. Controller::requestAction(), and passing in a param that either auto-renders the layout checked in the beforeFilter, seemed to solve my problem. Thanks :)
savant