Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 856 lines (743 sloc) 22.087 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
<?php
/**
* Represents a field in a form.
*
* A FieldList contains a number of FormField objects which make up the whole of a form.
* In addition to single fields, FormField objects can be "composite", for example, the {@link TabSet}
* field. Composite fields let us define complex forms without having to resort to custom HTML.
*
* <b>Subclassing</b>
*
* Define a {@link dataValue()} method that returns a value suitable for inserting into a single database field.
* For example, you might tidy up the format of a date or currency field.
* Define {@link saveInto()} to totally customise saving.
* For example, data might be saved to the filesystem instead of the data record,
* or saved to a component of the data record instead of the data record itself.
*
* @package forms
* @subpackage core
*/
class FormField extends RequestHandler {

/**
* @var Form
*/
protected $form;

protected $name, $title, $value ,$message, $messageType, $extraClass;

/**
* @var $description string Adds a "title"-attribute to the markup.
* @todo Implement in all subclasses
*/
protected $description;

/**
* @var $extraClasses array Extra CSS-classes for the formfield-container
*/
protected $extraClasses;

public $dontEscape;

/**
* @var $rightTitle string Used in SmallFieldHolder() to force a right-aligned label.
*/
protected $rightTitle;

/**
* @var $leftTitle string Used in SmallFieldHolder() to force a left-aligned label with correct spacing.
* Please use $title for FormFields rendered with FieldHolder().
*/
protected $leftTitle;

/**
* Stores a reference to the FieldList that contains this object.
* @var FieldList
*/
protected $containerFieldSet;

/**
* @var boolean
*/
protected $readonly = false;

/**
* @var boolean
*/
protected $disabled = false;

/**
* @var string custom validation message for the Field
*/
protected $customValidationMessage = "";

/**
* Name of the template used to render this form field. If not set, then
* will look up the class ancestry for the first matching template where
* the template name equals the class name.
*
* To explicitly use a custom template or one named other than the form
* field see {@link setTemplate()}, {@link setFieldHolderTemplate()}
*
* @var string
*/
protected
$template,
$fieldHolderTemplate,
  $smallFieldHolderTemplate;

/**
* @var array All attributes on the form field (not the field holder).
* Partially determined based on other instance properties, please use {@link getAttributes()}.
*/
protected $attributes = array();

/**
* Takes a fieldname and converts camelcase to spaced
* words. Also resolves combined fieldnames with dot syntax
* to spaced words.
*
* Examples:
* - 'TotalAmount' will return 'Total Amount'
* - 'Organisation.ZipCode' will return 'Organisation Zip Code'
*
* @param string $fieldName
* @return string
*/
public static function name_to_label($fieldName) {
if(strpos($fieldName, '.') !== false) {
$parts = explode('.', $fieldName);
$label = $parts[count($parts)-2] . ' ' . $parts[count($parts)-1];
} else {
$label = $fieldName;
}
$label = preg_replace("/([a-z]+)([A-Z])/","$1 $2", $label);

return $label;
}

/**
* Create a new field.
* @param name The internal field name, passed to forms.
* @param title The field label.
* @param value The value of the field.
*/
function __construct($name, $title = null, $value = null) {
$this->name = $name;
$this->title = ($title === null) ? $name : $title;

if($value !== NULL) $this->setValue($value);

parent::__construct();
}

/**
* Return a Link to this field
*/
function Link($action = null) {
return Controller::join_links($this->form->FormAction(), 'field/' . $this->name, $action);
}

/**
* Returns the HTML ID of the field - used in the template by label tags.
* The ID is generated as FormName_FieldName. All Field functions should ensure
* that this ID is included in the field.
*/
function ID() {
$name = preg_replace('/(^-)|(-$)/', '', preg_replace('/[^A-Za-z0-9_-]+/', '-', $this->name));
if($this->form) return $this->form->FormName() . '_' . $name;
else return $name;
}

/**
* Returns the field name - used by templates.
*
* @return string
*/
function getName() {
return $this->name;
}

/**
* @deprecated 3.0 Use {@link getName()}.
*/
public function Name() {
Deprecation::notice('3.0', 'Use getName() instead.');
return $this->getName();
}

/**
* Returns the field message, used by form validation.
* Use {@link setError()} to set this property.
*
* @return string
*/
function Message() {
return $this->message;
}

/**
* Returns the field message type, used by form validation.
* Arbitrary value which is mostly used for CSS classes
* in the rendered HTML, e.g. "required".
* Use {@link setError()} to set this property.
*
* @return string
*/
function MessageType() {
return $this->messageType;
}

/**
* Returns the field value - used by templates.
*/
function Value() {
return $this->value;
}

/**
* Method to save this form field into the given data object.
* By default, makes use of $this->dataValue()
*/
function saveInto(DataObjectInterface $record) {
if($this->name) {
$record->setCastedField($this->name, $this->dataValue());
}
}

/**
* Returns the field value suitable for insertion into the data object
*/
function dataValue() {
return $this->value;
}

/**
* Returns the field label - used by templates.
*/
function Title() {
return $this->title;
}

function setTitle($val) {
$this->title = $val;
return $this;
}

function RightTitle() {
return $this->rightTitle;
}

function setRightTitle($val) {
$this->rightTitle = $val;
return $this;
}

function LeftTitle() {
return $this->leftTitle;
}

function setLeftTitle($val) {
$this->leftTitle = $val;
return $this;
}

/**
* Set tabindex HTML attribute
* (defaults to none).
*
* @deprecated 3.0 Use setAttribute("tabindex") instead
* @param int $index
*/
public function setTabIndex($index) {
Deprecation::notice('3.0', 'Use setAttribute("tabindex") instead');
$this->setAttribute($index);
return $this;
}

/**
* Get tabindex (if previously set)
*
* @deprecated 3.0 Use getAttribute("tabindex") instead
* @return int
*/
public function getTabIndex() {
Deprecation::notice('3.0', 'Use getAttribute("tabindex") instead');
return $this->getAttribute('tabindex');
}

/**
* Compiles all CSS-classes. Optionally includes a "nolabel"-class
* if no title was set on the formfield.
* Uses {@link Message()} and {@link MessageType()} to add validatoin
* error classes which can be used to style the contained tags.
*
* @return string CSS-classnames
*/
function extraClass() {
$classes = array();

$classes[] = $this->Type();

if($this->extraClasses) $classes = array_merge($classes, array_values($this->extraClasses));

// Allow customization of label and field tag positioning
if(!$this->Title()) $classes[] = "nolabel";

// Allow custom styling of any element in the container based
// on validation errors, e.g. red borders on input tags.
// CSS-Class needs to be different from the one rendered
// through {@link FieldHolder()}
if($this->Message()) $classes[] .= "holder-" . $this->MessageType();

return implode(' ', $classes);
}

/**
* Add a CSS-class to the formfield-container.
*
* @param $class String
*/
function addExtraClass($class) {
$this->extraClasses[$class] = $class;
return $this;
}

/**
* Remove a CSS-class from the formfield-container.
*
* @param $class String
*/
function removeExtraClass($class) {
if(isset($this->extraClasses) && array_key_exists($class, $this->extraClasses)) unset($this->extraClasses[$class]);
return $this;
}

/**
* Set an HTML attribute on the field element, mostly an <input> tag.
*
* Some attributes are best set through more specialized methods, to avoid interfereing with built-in behaviour:
* - 'class': {@link addExtraClass()}
* - 'title': {@link setDescription()}
* - 'value': {@link setValue}
* - 'name': {@link setName}
*
* CAUTION Doesn't work on most fields which are composed of more than one HTML form field:
* AjaxUniqueTextField, CheckboxSetField, ComplexTableField, CompositeField, ConfirmedPasswordField, CountryDropdownField,
* CreditCardField, CurrencyField, DateField, DatetimeField, FieldGroup, GridField, HtmlEditorField,
* ImageField, ImageFormAction, InlineFormAction, ListBoxField, etc.
*
* @param string
* @param string
*/
function setAttribute($name, $value) {
$this->attributes[$name] = $value;
return $this;
}

/**
* Get an HTML attribute defined by the field, or added through {@link setAttribute()}.
* Caution: Doesn't work on all fields, see {@link setAttribute()}.
*
* @return string
*/
function getAttribute($name) {
$attrs = $this->getAttributes();
return @$attrs[$name];
}

/**
* @return array
*/
function getAttributes() {
$attrs = array(
'type' => 'text',
'name' => $this->getName(),
'value' => $this->Value(),
'class' => $this->extraClass(),
'id' => $this->ID(),
'disabled' => $this->isDisabled(),
'title' => $this->getDescription(),
);

return array_merge($attrs, $this->attributes);
}

/**
* @param Array Custom attributes to process. Falls back to {@link getAttributes()}.
* If at least one argument is passed as a string, all arguments act as excludes by name.
* @return string HTML attributes, ready for insertion into an HTML tag
*/
function getAttributesHTML($attrs = null) {
$exclude = (is_string($attrs)) ? func_get_args() : null;

if(!$attrs || is_string($attrs)) $attrs = $this->getAttributes();

// Remove empty
$attrs = array_filter((array)$attrs, function($v) {
return ($v || $v === 0 || $v === '0');
});

// Remove excluded
if($exclude) $attrs = array_diff_key($attrs, array_flip($exclude));

// Create markkup
$parts = array();
foreach($attrs as $name => $value) {
$parts[] = ($value === true) ? "{$name}=\"{$name}\"" : "{$name}=\"" . Convert::raw2att($value) . "\"";
}

return implode(' ', $parts);
}

/**
* Returns a version of a title suitable for insertion into an HTML attribute
*/
function attrTitle() {
return Convert::raw2att($this->title);
}
/**
* Returns a version of a title suitable for insertion into an HTML attribute
*/
function attrValue() {
return Convert::raw2att($this->value);
}

/**
* Set the field value.
* Returns $this.
*/
function setValue($value) {
$this->value = $value; return $this;
return $this;
}

/**
* Set the field name
*/
function setName($name) {
$this->name = $name;
return $this;
}

/**
* Set the container form.
* This is called whenever you create a new form and put fields inside it, so that you don't
* have to worry about linking the two.
*/
function setForm($form) {
$this->form = $form;
return $this;
}

/**
* Get the currently used form.
*
* @return Form
*/
function getForm() {
return $this->form;
}

/**
* Return TRUE if security token protection is enabled on the parent {@link Form}.
*
* @return bool
*/
public function securityTokenEnabled() {
$form = $this->getForm();
if(!$form) return false;

return $form->getSecurityToken()->isEnabled();
}

/**
* Sets the error message to be displayed on the form field
* Set by php validation of the form
*/
function setError($message, $messageType) {
$this->message = $message;
$this->messageType = $messageType;

return $this;
}

/**
* Set the custom error message to show instead of the default
* format of Please Fill In XXX. Different from setError() as
* that appends it to the standard error messaging
*
* @param string Message for the error
*/
public function setCustomValidationMessage($msg) {
$this->customValidationMessage = $msg;

return $this;
}

/**
* Get the custom error message for this form field. If a custom
* message has not been defined then just return blank. The default
* error is defined on {@link Validator}.
*
* @todo Should the default error message be stored here instead
* @return string
*/
public function getCustomValidationMessage() {
return $this->customValidationMessage;
}

/**
* Set name of template (without path or extension).
* Caution: Not consistently implemented in all subclasses,
* please check the {@link Field()} method on the subclass for support.
*
* @param string
*/
function setTemplate($template) {
$this->template = $template;

return $this;
}

/**
* @return string
*/
function getTemplate() {
return $this->template;
}

/**
* @return string
*/
public function getFieldHolderTemplate() {
return $this->fieldHolderTemplate;
}

/**
* Set name of template (without path or extension) for the holder,
* which in turn is responsible for rendering {@link Field()}.
*
* Caution: Not consistently implemented in all subclasses,
* please check the {@link Field()} method on the subclass for support.
*
* @param string
*/
public function setFieldHolderTemplate($template) {
$this->fieldHolderTemplate = $template;

return $this;
}

/**
* @return string
*/
public function getSmallFieldHolderTemplate() {
return $this->smallFieldHolderTemplate;
}

/**
* Set name of template (without path or extension) for the small holder,
* which in turn is responsible for rendering {@link Field()}.
*
* Caution: Not consistently implemented in all subclasses,
* please check the {@link Field()} method on the subclass for support.
*
* @param string
*/
public function setSmallFieldHolderTemplate($template) {
$this->smallFieldHolderTemplate = $template;

return $this;
}

/**
* Returns the form field - used by templates.
* Although FieldHolder is generally what is inserted into templates, all of the field holder
* templates make use of $Field. It's expected that FieldHolder will give you the "complete"
* representation of the field on the form, whereas Field will give you the core editing widget,
* such as an input tag.
*
* @param array $properties key value pairs of template variables
* @return string
*/
function Field($properties = array()) {
$obj = ($properties) ? $this->customise($properties) : $this;

return $obj->renderWith($this->getTemplates());
}

/**
* Returns a "field holder" for this field - used by templates.
*
* Forms are constructed by concatenating a number of these field holders.
* The default field holder is a label and a form field inside a div.
* @see FieldHolder.ss
*
* @param array $properties key value pairs of template variables
* @return string
*/
function FieldHolder($properties = array()) {
$obj = ($properties) ? $this->customise($properties) : $this;

return $obj->renderWith($this->getFieldHolderTemplates());
}

   /**
* Returns a restricted field holder used within things like FieldGroups.
*
* @param array $properties
*
* @return string
*/
   function SmallFieldHolder($properties = array()) {
$obj = ($properties) ? $this->customise($properties) : $this;

return $obj->renderWith($this->getSmallFieldHolderTemplates());
}

/**
* Returns an array of templates to use for rendering {@link FieldH}
*
* @return array
*/
public function getTemplates() {
return $this->_templates($this->getTemplate());
}

/**
* Returns an array of templates to use for rendering {@link FieldHolder}
*
* @return array
*/
public function getFieldHolderTemplates() {
return $this->_templates(
$this->getFieldHolderTemplate(),
'_holder'
);
}

/**
* Returns an array of templates to use for rendering {@link SmallFieldHolder}
*
* @return array
*/
public function getSmallFieldHolderTemplates() {
return $this->_templates(
$this->getSmallFieldHolderTemplate(),
'_holder_small'
);
}


/**
* Generate an array of classname strings to use for rendering this form
* field into HTML
*
* @param string $custom custom template (if set)
* @param string $suffix template suffix
*
* @return array $stack a stack of
*/
private function _templates($custom = null, $suffix = null) {
$matches = array();

foreach(array_reverse(ClassInfo::ancestry($this)) as $className) {
$matches[] = $className . $suffix;

if($className == "FormField") break;
}

if($custom) array_unshift($matches, $custom);

return $matches;
}

/**
* Returns true if this field is a composite field.
* To create composite field types, you should subclass {@link CompositeField}.
*/
function isComposite() {
return false;
}

/**
* Returns true if this field has its own data.
* Some fields, such as titles and composite fields, don't actually have any data. It doesn't
* make sense for data-focused methods to look at them. By overloading hasData() to return false,
* you can prevent any data-focused methods from looking at it.
*
* @see FieldList::collateDataFields()
*/
function hasData() {
return true;
}

/**
* @return boolean
*/
function isReadonly() {
return $this->readonly;
}

/**
* Sets readonly-flag on form-field. Please use performReadonlyTransformation()
* to actually transform this instance.
* @param $bool boolean Setting "false" has no effect on the field-state.
*/
function setReadonly($bool) {
$this->readonly = $bool;
return $this;
}

/**
* @return boolean
*/
function isDisabled() {
return $this->disabled;
}

/**
* Sets disabed-flag on form-field. Please use performDisabledTransformation()
* to actually transform this instance.
* @param $bool boolean Setting "false" has no effect on the field-state.
*/
function setDisabled($bool) {
$this->disabled = $bool;
return $this;
}

/**
* Returns a readonly version of this field
*/
function performReadonlyTransformation() {
$field = new ReadonlyField($this->name, $this->title, $this->value);
$field->addExtraClass($this->extraClass());
$field->setForm($this->form);
return $field;
}

/**
* Return a disabled version of this field.
* Tries to find a class of the class name of this field suffixed with "_Disabled",
* failing that, finds a method {@link setDisabled()}.
*
* @return FormField
*/
function performDisabledTransformation() {
$clone = clone $this;
$disabledClassName = $clone->class . '_Disabled';
if(ClassInfo::exists($disabledClassName)) {
return new $disabledClassName($this->name, $this->title, $this->value);
} else {
$clone->setDisabled(true);
return $clone;
}
}

function transform(FormTransformation $trans) {
return $trans->transform($this);
}

function hasClass($class){
$patten = '/'.strtolower($class).'/i';
$subject = strtolower($this->class." ".$this->extraClass());
return preg_match($patten, $subject);
}

/**
* Returns the field type - used by templates.
* The field type is the class name with the word Field dropped off the end, all lowercase.
* It's handy for assigning HTML classes. Doesn't signify the <input type> attribute,
* see {link getAttributes()}.
*
* @return string
*/
function Type() {
return strtolower(preg_replace('/Field$/', '', $this->class));
}

/**
* Construct and return HTML tag.
*
* @deprecated 3.0 Please define your own FormField template using {@link setFieldTemplate()}
* and/or {@link renderFieldTemplate()}
*
* @todo Transform to static helper method.
*/
function createTag($tag, $attributes, $content = null) {
$preparedAttributes = '';
foreach($attributes as $k => $v) {
// Note: as indicated by the $k == value item here; the decisions over what to include in the attributes can sometimes get finicky
if(!empty($v) || $v === '0' || $k == 'value') $preparedAttributes .= " $k=\"" . Convert::raw2att($v) . "\"";
}

if($content || $tag != 'input') return "<$tag$preparedAttributes>$content</$tag>";
else return "<$tag$preparedAttributes />";
}

/**
* Abstract method each {@link FormField} subclass must implement,
* determines whether the field is valid or not based on the value.
* @todo Make this abstract.
*
* @param Validator
* @return boolean
*/
function validate($validator) {
return true;
}

/**
* @deprecated 3.0 Use setDescription()
*/
function describe($description) {
Deprecation::notice('3.0', 'Use setDescription()');
$this->setDescription($description);
return $this;
}

/**
* Describe this field, provide help text for it.
* By default, renders as a "title" attribute on the form field.
*
* @return string Description
*/
function setDescription($description) {
$this->description = $description;
return $this;
}

/**
* @return string
*/
function getDescription() {
return $this->description;
}

function debug() {
return "$this->class ($this->name: $this->title : <font style='color:red;'>$this->message</font>) = $this->value";
}

/**
* This function is used by the template processor. If you refer to a field as a $ variable, it
* will return the $Field value.
*/
function forTemplate() {
return $this->Field();
}

/**
* @uses Validator->fieldIsRequired()
* @return boolean
*/
function Required() {
if($this->form && ($validator = $this->form->Validator)) {
return $validator->fieldIsRequired($this->name);
}
}

/**
* Set the FieldList that contains this field.
*
* @param FieldList $containerFieldSet
*/
function setContainerFieldSet($containerFieldSet) {
$this->containerFieldSet = $containerFieldSet;
return $this;
}

function rootFieldSet() {
if(is_object($this->containerFieldSet)) return $this->containerFieldSet->rootFieldSet();
else user_error("rootFieldSet() called on $this->class object without a containerFieldSet", E_USER_ERROR);
}

}
Something went wrong with that request. Please try again.