Skip to content

Instantly share code, notes, and snippets.

@gunderwonder
Created September 15, 2010 18:32
Show Gist options
  • Save gunderwonder/581199 to your computer and use it in GitHub Desktop.
Save gunderwonder/581199 to your computer and use it in GitHub Desktop.
Complete Cobweb form example
<?php
// the form...
class WikiWordForm extends Form {
private $word = NULL;
// declarative field configuration; this is where you define the form...
public function configure() {
$this->title = new TextField();
// validate as slug with max length, custom label
$this->wikiword = new SlugField(array('label' => 'Slug', 'max_length' => 512));
$this->body = new TextField(array('widget' => new TextareaInput())); // render as <textarea>
}
// override constructor to get wiki word instance...
public function __construct($word, $form_data = NULL, array $properties = array()) {
$this->word = $word;
parent::__construct($form_data, $properties);
}
// custom validator for checking uniqueness...
protected function cleanWikiword($word) {
if (!$this->word->exists() && Model::table('WikiWord')->findOneByWikiWord($word))
throw new FormValidationException(__('Wiki word exists, choose another...'));
return $word;
}
// save form data to model instance
public function save($commit = true) {
$data = $this->cleanData(); // valid, normalized data
foreach ($data as $key => $value)
$this->word->$key = $value;
if (!$this->word->exists())
$this->word->created = CWDateTime::create();
if ($commit)
$this->word->save();
}
}
class WikiWordController extends Controller {
// create/edit controller action
public function edit($id = NULL) {
$word = $id ? Model::table('WikiWord')->find($id) : new WikiWord();
if (!$word)
throw new HTTP404();
$form = NULL;
if ($this->isPOST()) {
// "bind" POST data to form
$form = new WikiWordForm($word, $this->POST);
// if valid, commit to database
if ($form->isValid())
$form->save();
} else {
$form = new WikiWordForm($word);
}
return $this->render('edit_form.php', compact('form', 'word'));
}
}
// template...
?>
<form action="edit<?php if ($word->exists()): echo '/' . $word->id; endif ?>">
<?php if ($request->isPOST() && !$form->isValid()): ?>
<div class="validation-error">The form is invalid, bla, bla.</div>
<?php endif ?>
<?php foreach ($form as $field): ?>
<div>
<?php
echo $field->renderLabel();
echo $field->render();
?>
<?php if (!$field->isValid()): ?>
<div class="validation-error">
<?php echo implode($field->errors(), '<br />' ?><!-- "Enter a valid slug.", "This field is required", etc -->
</div>
<?php endif ?>
</div>
<?php endforeach ?>
<input type="submit" />
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment