Field / $field

Represents a custom field that is used on a Page

Field objects are managed by the $fields API variable. Every field has a name, a type (Fieldtype), and optional settings that control how it behaves in the admin and on the front-end.

// Get a field
$field = $fields->get('body');
echo $field->name;   // body
echo $field->type;   // FieldtypeTextarea
echo $field->label;  // Body
Constants

Flags are bitmask values that can be combined and checked with hasFlag(), addFlag(), and removeFlag().

ConstantValueDescription
flagAutojoin1Field is automatically joined to the page at load time (if supported)
flagGlobal4Field used by all fieldgroups — all fieldgroups required to contain it
flagSystem8Field is a system field — cannot be deleted, renamed, or converted
flagPermanent16Field is permanent in any fieldgroups/templates where it exists
flagAccess32Field is access controlled
flagAccessAPI64Access-controlled values are still front-end API accessible
flagAccessEditor128Non-editable values can still be viewed in the editor
flagUnique256Field requires unique values in its data column 3.0.150
flagFieldgroupContext2048Field is in runtime context for a specific fieldgroup
flagSystemOverride32768Override that allows removal of system/permanent flags
Native properties
PropertyTypeDescription
idintNumeric ID of field in the database
namestringName of field
tablestringDatabase table used by the field (read-only)
typeFieldtype or nullFieldtype module representing the type of this field
flagsintBitmask of flags
flagsStrstringNames of flags as space-separated string (read-only)
labelstringText label for the field
descriptionstringLonger description text
notesstringAdditional notes text
iconstringIcon name
tagsstringSpace-separated tags string
tagListarrayTags as an array (read-only)
prevNamestringPrevious name (if field was renamed)
prevTablestringPrevious table name (if field was renamed)
prevFieldtypeFieldtype or nullPrevious Fieldtype (if type was changed)

Inputfield native and custom properties are also stored on Field objects, as are custom configuration properties from the Fieldtype. Below are examples of some common native properties from Inputfield:

PropertyTypeDescription
requiredint or bool or nullWhether the field is required during input
requiredIfstring or nullSelector string defining conditions when input is required
showIfstring or nullSelector string defining conditions when Inputfield is shown
columnWidthint or nullInputfield column width (percent) 10-100
collapsedint or nullInputfield collapsed value (see Inputfield constants)
Retrieval

get($key)

Get a field setting or dynamic data property.

$name = $field->get('name');
$label = $field->get('label');

getFieldtype()

Return the Fieldtype module for this field. Same as $field->type.

$fieldtype = $field->getFieldtype();

getTable()

Get the database table name used by this field. The table name is field_ prefixed with the field name, truncated to 64 characters max.

echo $field->getTable(); // field_body

getLabel($language = null) / getDescription($language = null) / getNotes($language = null)

Get the label, description, or notes for the current language (or a specified language in multi-language environments). Unlike $field->label, these methods are language-aware.

echo $field->getLabel();
echo $field->getDescription();
echo $field->getNotes();

getIcon($prefix = false)

Get the icon name. When $prefix is true, returns with fa- prefix.

echo $field->getIcon();       // cog
echo $field->getIcon(true);   // fa-cog

getFieldgroups()

Return the list of Fieldgroups using this field.

$fieldgroups = $field->getFieldgroups();

getTemplates()

Return the list of Templates using this field.

$templates = $field->getTemplates();

numFieldgroups()

Return the number of Fieldgroups this field is used in.

$count = $field->numFieldgroups();

getContext($for, $namespace = '')

Get this field in context of a Page, Template, or Fieldgroup.

$fieldContext = $field->getContext($template);

hasContext($for, $namespace = '')

Check if this field has context settings for the given Page, Template, or Fieldgroup.

if($field->hasContext($template)) {
    // field has per-template context settings
}

getInputfield(Page $page, $contextStr = '')

Get the Inputfield module used to collect input for this field on the given page.

$inputfield = $field->getInputfield($page);

getConfigInputfields()

Get Inputfields needed to configure this field in the admin. Returns an InputfieldWrapper (a fieldset containing Inputfield instances).

$configInputfields = $field->getConfigInputfields();

editUrl($options = [])

Get URL to edit this field in the admin.

echo $field->editUrl(); // /admin/setup/field/edit?id=123
echo $field->editUrl('description'); // with #find-description anchor
echo $field->editUrl(['http' => true]); // with full scheme and hostname
Manipulation

set($key, $value)

Set a native setting or dynamic data property. Also available via property assignment.

$field->set('label', 'New Label');
// or
$field->label = 'New Label';

setName($name)

Set the field's name. Throws WireException for reserved words, duplicate names, system fields, or invalid formats. When renaming, the previous name is tracked in prevName and the previous table in prevTable.

$field->setName('new_name');

setFieldtype($type)

Set the field's type. Accepts a Fieldtype object or a string class name. Supports setup names via FieldtypeName.setupName syntax. When changing type, the previous Fieldtype is tracked in prevFieldtype.

$field->setFieldtype('FieldtypeText');
$field->setFieldtype('FieldtypeImage.lightbox'); // with setup name

save()

Save the field's settings and data to the database. To hook this, hook to Fields::save() instead.

$field->save();

setLabel($text, $language = null) / setDescription($text, $language = null) / setNotes($text, $language = null)

Set label, description, or notes, optionally for a specific language in multi-language environments.

$field->setLabel('My Label');
$field->setDescription('Long description', $language);

setIcon($icon)

Set the icon for this field. The fa- or icon- prefix is stripped automatically.

$field->setIcon('fa-cog');
$field->setIcon('icon-home');
$field->setIcon('user'); // all equivalent

setTable($table = null)

Set an override table name, or pass null to restore the default. The table name is sanitized and truncated to 64 characters.

$field->setTable('custom_table');
$field->setTable(null); // restore default
Flags

addFlag($flag)

Add a bitmask flag to the field. Returns $this for chaining.

$field->addFlag(Field::flagAutojoin);

removeFlag($flag)

Remove a bitmask flag from the field. System and permanent flags cannot be removed without first adding flagSystemOverride. Returns $this for chaining.

$field->removeFlag(Field::flagAutojoin);

To remove a system or permanent flag, add flagSystemOverride first:

$field->addFlag(Field::flagSystemOverride);
$field->removeFlag(Field::flagSystem);
$field->removeFlag(Field::flagSystemOverride);
$field->save();

This is intentionally indirect to prevent accidental removal of system field protections.

hasFlag($flag)

Check if the field has the given bitmask flag.

if($field->hasFlag(Field::flagSystem)) {
    echo "This is a system field";
}
Access control

$useRoles

Boolean property that enables or disables access control. Setting to true adds flagAccess; setting to false removes it.

$field->useRoles = true;  // enable access control
$field->useRoles = false; // disable access control

$editRoles / $viewRoles

Arrays of Role IDs with edit or view access. Applicable only when useRoles is true.

$field->editRoles = [1, 2]; // role IDs
$field->viewRoles = [1];

setRoles($type, $roles)

Set the roles allowed to view or edit this field. $type is 'view' or 'edit'. Accepts an array of Role IDs, Role objects, or role names.

$field->setRoles('edit', [1, 2]);
$field->setRoles('view', ['guest']);

viewable(Page $page = null, User $user = null)

Check if the field is viewable on the given page by the given user. To maximize efficiency, check $field->useRoles first. Note: this does not check that the page itself is viewable — use $page->viewable() for that. Note there is also $page->viewable($field).

if($field->viewable($page)) {
    echo $page->get($field->name);
}

editable(Page $page = null, User $user = null)

Check if the field is editable on the given page by the given user. To maximize efficiency, check $field->useRoles first. Note: this does not check that the page itself is editable — use $page->editable() or $page->editable($field) for that.

if($field->editable($page)) {
    // user can edit this field on this page
}
Tags

Tags are space-separated strings stored on the field. Tag lookups are case-insensitive.

$tags / $tagList

The tags property returns a space-separated string. The tagList property returns an array (read-only).

echo $field->tags;   // "foo bar"
print_r($field->tagList); // ['foo' => 'foo', 'bar' => 'bar']

getTags($getString = false)

Get tags as an array, or as a space-separated string when $getString is true.

$tags = $field->getTags();        // array
$tagsStr = $field->getTags(true); // "foo bar"

setTags($tagList, $reindex = true)

Set all tags at once. Accepts an array or space-separated string.

$field->setTags(['foo', 'bar']);
$field->setTags('foo bar');

addTag($tag)

Add a single tag. Returns the current tag list.

$field->addTag('featured');

removeTag($tag)

Remove a tag. Returns the current tag list.

$field->removeTag('featured');

hasTag($tag)

Check if the field has the given tag (case-insensitive).

if($field->hasTag('featured')) {
    // field has the "featured" tag
}
Hooks

Hookable methods on Field itself:

HookWhenArguments
Field::viewableBefore checking if field is viewable$page, $user
Field::editableBefore checking if field is editable$page, $user
Field::getInputfieldWhen building the Inputfield for a page$page, $contextStr
Field::getConfigInputfieldsWhen building config Inputfields for admin

Hooks Fields / $fields (WireSaveableItems) which receive Field objects:

HookWhenArguments
Fields::saveReadyRight before field is saved (confirmed)$field
Fields::savedRight after field has been saved$field, $changes
Fields::addedRight after a new field has been added$field
Fields::deleteReadyRight before field is deleted (confirmed)$field
Fields::deletedRight after field has been deleted$field
Fields::renameReadyRight before field is renamed$field, $oldName, $newName
Fields::renamedRight after field has been renamed$field, $oldName, $newName
Fields::cloneReadyRight before field is cloned$field, $copy
Fields::clonedRight after field has been cloned$field, $copy
// Example: log when any field is saved
$wire->addHookAfter('Fields::saved', function(HookEvent $event) {
    $field = $event->arguments(0);
    $changes = $event->arguments(1);
    // ...
});
Notes
  • Field objects are managed by the $fields API variable ($fields->get(), $fields->save(), etc.).
  • Manipulations to a Field are not saved until $field->save() is called.
  • The __toString() method returns the field name.
  • System fields (with flagSystem) cannot be renamed or deleted. Use flagSystemOverride to override.
  • The database table name is field_ + field name, truncated to 64 characters.
  • Setting useRoles to true/false automatically adds/removes flagAccess.
  • Tag operations are case-insensitive — adding "Foo" when "foo" exists will not duplicate.
  • getLabel() returns the field name when no label is set.
  • Source file: wire/core/Field/Field.php.
API reference: methods, properties, hooks, constants
// Get an instance of Field
$field = $fields->get('field_name');

Field objects are managed by the $fields API variable.


Click any linked item for full usage details and examples. Hookable methods are indicated with the icon. In addition to those shown below, the Field class also inherits all the methods and properties of: WireData and Wire.

Show $var?     Show args?       Only hookable?    

Retrieval

NameReturnSummary 
$field->get(string $key)
mixed

Get a Field setting or dynamic data property

 
$field->getConfigInputfields()
InputfieldWrapper

Get any Inputfields needed to configure the field in the admin.

$field->getContext($for)
Field bool

Get this field in context of a Page/Template

 
$field->getDescription()
string

Return field description for current language, or another specified language.

 
$field->getFieldgroups()
FieldgroupsArray int

Return the list of Fieldgroups using this field.

 
$field->getFieldtype()
Fieldtype null string

Return the Fieldtype module representing this field’s type.

 
$field->getIcon()
mixed string

Return the icon used by this field, or blank if none.

 
$field->getInputfield(Page $page)
Inputfield null

Get the Inputfield module used to collect input for this field.

$field->getLabel()
string

Get field label for current language, or another specified language.

 
$field->getNotes()
string

Return field notes for current language, or another specified language.

 
$field->getTable()
string

Get the database table used by this field.

 
$field->getTemplates()
TemplatesArray int

Return the list of of Templates using this field.

 
$field->hasContext($for)
Field bool

Does this field have context settings for given Page/Template?

 
$field->numFieldgroups()
int

Return the number of Fieldgroups this field is used in.

 

Access

NameReturnSummary 
$field->editRoles array Role IDs with edit access, applicable only if access control is enabled.  
$field->editable()
bool

Is this field editable?

$field->useRoles bool Whether or not access control is enabled  
$field->viewRoles array Role IDs with view access, applicable only if access control is enabled.  
$field->viewable()
bool

Is this field viewable?

Advanced

NameReturnSummary 
$field->setTable()
None

Set an override table name, or omit (or null) to restore default table name

 

Flags

NameReturnSummary 
$field->addFlag(int $flag)
$this

Add the given bitmask flag

 
Field::flagAccess const32Field is access controlled 
Field::flagAccessAPI const64If field is access controlled, this flag says that values are still front-end API accessible Without this flag, non-viewable values are made blank when output formatting is ON. 
Field::flagAccessEditor const128If field is access controlled and user has no edit access, they can still view in the editor (if they have view permission) Without this flag, non-editable values are simply not shown in the editor at all. 
Field::flagAutojoin const1Field should be automatically joined to the page at page load time 
Field::flagFieldgroupContext const2048Field has been placed in a runtime state where it is contextual to a specific fieldgroup and is no longer saveable 
Field::flagGlobal const4Field used by all fieldgroups - all fieldgroups required to contain this field 
Field::flagPermanent const16Field is permanent in any fieldgroups/templates where it exists - it may not be removed from them 
Field::flagSystem const8Field is a system field and may not be deleted, have it's name changed, or be converted to non-system 
Field::flagSystemOverride const32768Set this flag to override system/permanent flags if necessary - once set, system/permanent flags can be removed, but not in the same set(). 
Field::flagUnique const256Field requires that the same value is not repeated more than once in its table 'data' column (when supported by Fieldtype) When this flag is set and there is a non-empty $flagUnique property on the field, then it indicates a unique index is currently present. When only this flag is present (no property), it indicates a request to remove the index and flag. When only the property is present (no flag), it indicates a pending request to add unique index and flag. @3.0.150  
$field->hasFlag(int $flag)
bool

Does this field have the given bitmask flag?

 
$field->removeFlag(int $flag)
$this

Remove the given bitmask flag

 

Properties

NameReturnSummary 
$field->allowContexts array Names of settings that are custom configured to be allowed for context.  
$field->collapsed int null The Inputfield 'collapsed' value (see Inputfield collapsed constants).  
$field->columnWidth int null The Inputfield column width (percent) 10-100.  
$field->description string Longer description text for the field  
$field->flags int Bitmask of flags used by this field  
$field->flagsStr string Names of flags used by this field (readonly)  
$field->icon string Icon name used by the field, if applicable  
$field->id int Numeric ID of field in the database  
$field->label string Text string representing the label of the field  
$field->name string Name of field  
$field->notes string Additional notes text about the field  
$field->prevFieldtype Fieldtype null Previous Fieldtype, if type was changed  
$field->prevName string Previously used name (if field was renamed), 3.0.164+  
$field->prevTable string Previously database table (if field was renamed)  
$field->required int bool null Whether or not this field is required during input  
$field->requiredIf string null A selector-style string that defines the conditions under which input is required  
$field->showIf string null A selector-style string that defines the conditions under which the Inputfield is shown  
$field->table string Database table used by the field  
$field->tagList array Same as $tags property, but as an array.  
$field->tags string Tags that represent this field, if applicable (space separated string).  
$field->textFormat int null The Inputfield 'textFormat' value (see Inputfield textFormat constants).  
$field->type Fieldtype null Fieldtype module that represents the type of this field  

Additional methods and properties

In addition to the methods and properties above, Field also inherits the methods and properties of these classes:

API reference based on ProcessWire core version 3.0.267