Code Drive-By: Edit Anywhere Component for CakePHP

8 Aug

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.

controller =& $controller;
			App::import('Model', 'Setting');
			$this->Setting = new Setting();
		}

		function read($field = null) {
			return $this->render($field);
		}

		function render($field = null)
		{
			$content = $this->Setting->findByField($field);

			if(!empty($content)) {
				return $this->output($field, $content['Setting']['value']);
			} else {
				return $this->output($field, '');
			}
		}

		function output($field, $str)
		{
			$output = $str;
			if($this->controller->u['User']['role'] == 'admin') {
				$output .= $this->editButton($field);
			}
			return nl2br($output);
		}

		function editButton($field) {
			return '';
		}
	}
?>

And my Settings Controller looks like:

Setting->findByField($field);

			if(!empty($content)) {
				$this->Setting->id = $content['Setting']['id'];
			}

			if(!empty($this->data))
			{
				$content['Setting'] = array(
					'field' => $field,
					'value' => $this->data['Setting']['value'],
				);

				$this->Setting->save($content);
				die($this->redirect($_REQUEST['r']));
			}

			$this->set(compact('field', 'content'));
		}
	}
?>
  • Romiz
    It`s cool decision! Inline editors rules!
    Whether you thought about automatic rendering of text blocks?
    I mean that view itself should to know what blocks needed and will call render method of some helper...
blog comments powered by Disqus