Avatar britg

all the web, gaming, and foodie stuff that’s fit to printf()

Code Drive-By: Edit Anywhere Component for CakePHP

I call this a code drive-by because I’m just going to dump the code without much explanation.  When I have time I’ll come back and walk through it and turn it into a useful article on the CakePHP bakery.

This component allows you to manage content (primarily text blocks) on a site if you’re logged in.  The editor pops up in a thickbox.

Some requirements off the top of my head:

  • CakePHP, duh.
  • jquery
  • thickbox
  • Auth Component

Again, sorry for the drive-by but hopefully someone will get use out of this.

  1.  
  2. <?php
  3.  
  4.   class ContentComponent extends Object
  5.   {
  6.     var $controller;
  7.     var $Setting;
  8.    
  9.     function initialize(&$controller)
  10.     {
  11.       $this->controller =& $controller;
  12.       App::import(‘Model’, ‘Setting’);
  13.       $this->Setting = new Setting();
  14.     }
  15.    
  16.     function read($field = null) {
  17.       return $this->render($field);
  18.     }
  19.    
  20.     function render($field = null)
  21.     {
  22.       $content = $this->Setting->findByField($field);
  23.      
  24.       if(!empty($content)) {
  25.         return $this->output($field, $content[‘Setting’][‘value’]);
  26.       } else {
  27.         return $this->output($field, );
  28.       }
  29.     }
  30.    
  31.     function output($field, $str)
  32.     {
  33.       $output = $str;
  34.       if($this->controller->u[‘User’][‘role’] == ‘admin’) {
  35.         $output .= $this->editButton($field);
  36.       }
  37.       return nl2br($output);
  38.     }
  39.    
  40.     function editButton($field) {
  41.       return ‘<a href="/settings/edit/’.$field.‘/?r=’.$_SERVER[‘REQUEST_URI’].‘" class="thickbox edit-button"><img src="/img/edit.png" width="10" height="10" /></a>’;
  42.     }
  43.   }
  44. ?>
  45.  

And my Settings Controller looks like:

  1.  
  2. <?php
  3.  
  4.   class SettingsController extends AppController
  5.   {
  6.     var $name = ‘Settings’;
  7.    
  8.     function edit($field)
  9.     {
  10.       $content = $this->Setting->findByField($field);
  11.      
  12.       if(!empty($content)) {
  13.         $this->Setting->id = $content[‘Setting’][‘id’];
  14.       }
  15.      
  16.       if(!empty($this->data))
  17.       {
  18.         $content[‘Setting’] = array(
  19.           ‘field’ => $field,
  20.           ‘value’ => $this->data[‘Setting’][‘value’],
  21.         );
  22.        
  23.         $this->Setting->save($content);
  24.         die($this->redirect($_REQUEST[‘r’]));
  25.       }
  26.      
  27.       $this->set(compact(‘field’, ‘content’));
  28.     }
  29.   }
  30. ?>
  31.  

 
close Reblog this comment
blog comments powered by Disqus

Passion Projects