class Member extends DataObject (View source)

The member class which represents the users of the system

Traits

Allows an object to have extensions applied to it.

A class that can be instantiated or replaced via DI

Provides extensions to this object to integrate it with standard config API methods.

Allows an object to declare a set of custom methods

Constants

CHANGE_NONE

Represents a field that hasn't changed (before === after, thus before == after)

CHANGE_STRICT

Represents a field that has changed type, although not the loosely defined value.

(before !== after && before == after) E.g. change 1 to true or "true" to true, but not true to 0. Value changes are by nature also considered strict changes.

CHANGE_VALUE

Represents a field that has changed the loosely defined value (before != after, thus, before !== after)) E.g. change false to true, but not false to 0

Properties

static private array $extensions

An array of extension names and parameters to be applied to this object upon construction.

from  Extensible
static private array $casting
static private string $default_cast

The default object to cast scalar fields to if casting information is not specified, and casting to an object is required.

from  ViewableData
static private string $singular_name

Human-readable singular name.

from  DataObject
static private string $plural_name

Human-readable plural name

from  DataObject
static private $api_access

Allow API access to this object?

from  DataObject
static private string $default_classname

Allows specification of a default value for the ClassName field.

from  DataObject
bool $destroyed from  DataObject
static private bool $validation_enabled

Should dataobjects be validated before they are written?

from  DataObject
static private array $fixed_fields

Base fields which are not defined in static $db

from  DataObject
static private array $cascade_deletes

List of relations that should be cascade deleted, similar to owns Note: This will trigger delete on many_many objects, not only the mapping table.

from  DataObject
static private array $db

Database field definitions.

from  DataObject
static private array $create_table_options

Specify custom options for a CREATE TABLE call.

from  DataObject
static private array $indexes

If a field is in this array, then create a database index on that field. This is a map from fieldname to index type.

from  DataObject
static private array $defaults

Inserts standard column-values when a DataObject is instantiated. Does not insert default records {see $default_records}.

from  DataObject
static private array $default_records

Multidimensional array which inserts default data into the database on a db/build-call as long as the database-table is empty. Please use this only for simple constructs, not for SiteTree-Objects etc. which need special behaviour such as publishing and ParentNodes.

from  DataObject
static private array $has_one

One-to-zero relationship defintion. This is a map of component name to data type. In order to turn this into a true one-to-one relationship you can add a {@link DataObject::$belongs_to} relationship on the child class.

from  DataObject
static private array $belongs_to

A meta-relationship that allows you to define the reverse side of a {@link DataObject::$has_one}.

from  DataObject
static private array $has_many

This defines a one-to-many relationship. It is a map of component name to the remote data class.

from  DataObject
static private array $many_many

many-many relationship definitions.

from  DataObject
static private array $many_many_extraFields

Extra fields to include on the connecting many-many table.

from  DataObject
static private array $belongs_many_many

The inverse side of a many-many relationship.

from  DataObject
static private string $default_sort

The default sort expression. This will be inserted in the ORDER BY clause of a SQL query if no other sort expression is provided.

from  DataObject
static private array $searchable_fields

Default list of fields that can be scaffolded by the ModelAdmin search interface.

from  DataObject
static private array $field_labels

User defined labels for searchable_fields, used to override default display in the search form.

from  DataObject
static private array $summary_fields
int $ID

ID of the DataObject, 0 if the DataObject doesn't exist in database.

from  DataObject
int $OldID

ID of object, if deleted

from  DataObject
string $Title from  DataObject
string $ClassName

Class name of the DataObject

from  DataObject
string $LastEdited

Date and time of DataObject's last modification.

from  DataObject
string $Created

Date and time of DataObject creation.

from  DataObject
string $ObsoleteClassName

If ClassName no longer exists this will be set to the legacy value

from  DataObject
static private bool $notify_password_change
static private array $hidden_fields

Internal-use only fields

static private array $title_format
static private string $unique_identifier_field

The unique field used to identify this member.

static private $password_expiry_days
static private bool $password_logging_enabled
static private int $lock_out_after_incorrect_logins
static private int $lock_out_delay_mins
$login_marker_cookie
static private bool $session_regenerate_id

Indicates that when a {@link Member} logs in, Member:session_regenerate_id() should be called as a security precaution.

static private int $temp_id_lifetime

Default lifetime of temporary ids.

static private int $auto_login_token_lifetime

Default lifetime of auto login token.

string $FirstName
string $Surname
string $Email
string $Password
string $TempIDHash
string $TempIDExpired
string $AutoLoginHash
string $AutoLoginExpired
string $PasswordEncryption
string $Salt
string $PasswordExpiry
string $LockedOutUntil
string $Locale
int $FailedLoginCount
string $DateFormat
string $TimeFormat

Methods

mixed
__call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

bool
hasMethod(string $method)

Return TRUE if a method exists on this object

array
allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

static bool
add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

static 
remove_extension(string $extension)

Remove an extension from a class.

static array
get_extensions(string $class = null, bool $includeArgumentString = false)

No description

static array|null
get_extra_config_sources(string $class = null)

Get extra config sources for this class

static bool
has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

array
invokeWithExtensions(string $method, mixed ...$arguments)

Calls a method if available on both this object and all applied {@link Extensions}, and then attempts to merge all results into an array

array
extend(string $method, mixed ...$arguments)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Extension|null
getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

bool
hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link has_extension()} to check if a class (not an instance) has a specific extension.

getExtensionInstances()

Get all extension instances for this specific object instance.

static Injectable
create(array ...$args)

An implementation of the factory method, allows you to create an instance of a class

static Injectable
singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

static Config_ForClass
config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

mixed
stat(string $name) deprecated

Get inherited config value

mixed
uninherited(string $name)

Gets the uninherited value for the given config option

$this
set_stat(string $name, mixed $value) deprecated

Update the config value for a given property

__construct(array|null $record = null, bool $isSingleton = false, array $queryParams = array())

Construct a new DataObject.

bool
__isset(string $property)

Check if a field exists on this object or its failover.

mixed
__get(string $property)

Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using {@link ViewableData::getField()}, then fall back on a failover object.

__set(string $property, mixed $value)

Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the {@link ViewableData::setField()} method.

setFailover(ViewableData $failover)

Set a failover object to attempt to get data from if it is not present on this object.

getFailover()

Get the current failover object if set

bool
hasField(string $field)

Returns true if the given field exists in a database column on any of the objects tables and optionally look up a dynamic getter with get().

mixed
getField(string $field)

Gets the value of a field.

$this
setField(string $fieldName, mixed $val)

Set the value of the field Called by {@link __set()} and any setFieldName() methods you might create.

defineMethods()

Adds methods from the extensions.

customise(array|ViewableData $data)

Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance with references to both this and the new custom data.

bool
exists()

Returns true if this object "exists", i.e., has a sensible value.

string
__toString()

No description

setCustomisedObj(ViewableData $object)

No description

string
castingHelper(string $field)

Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.

string
castingClass(string $field)

Get the class name a field on this object will be casted to.

string
escapeTypeForField(string $field)

Return the string-format type for the given field.

renderWith(string|array|SSViewer $template, array $customFields = null)

Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter:

  • a template name (e.g. Page)
  • an array of possible template names - the first valid one will be used
  • an SSViewer instance

object|DBField
obj(string $fieldName, array $arguments = [], bool $cache = false, string $cacheName = null)

Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.

object|DBField
cachedCall(string $field, array $arguments = [], string $identifier = null)

A simple wrapper around {@link ViewableData::obj()} that automatically caches the result so it can be used again without re-running the method.

bool
hasValue(string $field, array $arguments = null, bool $cache = true)

Returns true if the given method/parameter has a value (Uses the DBField::hasValue if the parameter is a database field)

string
XML_val(string $field, array $arguments = [], bool $cache = false)

Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.

array
getXMLValues(array $fields)

Get an array of XML-escaped values by field name

getIterator()

Return a single-item iterator so you can iterate over the fields of a single record.

array
getViewerTemplates(string $suffix = '')

Find appropriate templates for SSViewer to use to render this object

Me()

When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.

string
ThemeDir() deprecated

Return the directory if the current active theme (relative to the site root).

string
CSSClasses(string $stopAtClass = self::class)

Get part of the current classes ancestry to be used as a CSS class.

Debug()

Return debug information about this object that can be rendered into a template

getSchema()

Get schema object

destroy()

Destroy all of this objects dependant objects and local caches.

duplicate(bool $doWrite = true, array|null|false $relations = null)

Create a duplicate of this node. Can duplicate many_many relations

string
getObsoleteClassName()

Return obsolete class name, if this is no longer a valid class

string
getClassName()

Gets name of this class

$this
setClassName(string $className)

Set the ClassName attribute. {@link $class} is also updated.

newClassInstance(string $newClassName)

Create a new instance of a different class from this object's record.

bool
isEmpty()

Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).

string
i18n_pluralise(string $count)

Pluralise this item given a specific count.

string
singular_name()

Get the user friendly singular name of this DataObject.

string
i18n_singular_name()

Get the translated user friendly singular name of this DataObject same as singular_name() but runs it through the translating function

string
plural_name()

Get the user friendly plural name of this DataObject If the name is not defined (by renaming $plural_name in the subclass), this returns a pluralised version of the class name.

string
i18n_plural_name()

Get the translated user friendly plural name of this DataObject Same as plural_name but runs it through the translation function Translation string is in the form: $this->class.PLURALNAME Example: Page.PLURALNAME

string
getTitle()

Get the complete name of the member, by default in the format ", ".

data()

Returns the associated database record - in this case, the object itself.

array
toMap()

Convert this object to a map.

array
getQueriedDatabaseFields()

Return all currently fetched database fields.

update(array $data)

Update a number of fields on this object, given a map of the desired changes.

castedUpdate(array $data)

Pass changes as a map, and try to get automatic casting for these fields.

bool
merge(DataObject $rightObj, string $priority = 'right', bool $includeRelations = true, bool $overwriteWithEmpty = false)

Merges data and relations from another object of same class, without conflict resolution. Allows to specify which dataset takes priority in case its not empty.

$this
forceChange()

Forces the record to think that all its data has changed.

validate()

Validate this member object.

doValidate()

Public accessor for {see DataObject::validate()}

findCascadeDeletes(bool $recursive = true, ArrayList $list = null)

Find all objects that will be cascade deleted if this object is deleted

populateDefaults()

Ensure the locale is set to something sensible by default.

write(bool $showDebug = false, bool $forceInsert = false, bool $forceWrite = false, bool|array $writeComponents = false)

Writes all changes to this object to the database.

writeRelations()

Writes cached relation lists to the database, if possible

writeComponents(bool $recursive = false, array $skip = [])

Write the cached components to the database. Cached components could refer to two different instances of the same record.

delete()

Delete this data object.

static 
delete_by_id(string $className, int $id)

Delete the record with the given ID.

array
getClassAncestry()

Get the class ancestry, including the current class name.

getComponent(string $componentName)

Return a unary component object from a one to one relationship, as a DataObject.

$this
setComponent(string $componentName, DataObject|null $item)

Assign an item to the given component

getComponents(string $componentName, int|array $id = null)

Returns a one-to-many relation as a HasManyList

string
getRelationClass(string $relationName)

Find the foreign class of a relation on this DataObject, regardless of the relation type.

string
getRelationType(string $component)

Given a relation name, determine the relation type

inferReciprocalComponent(string $remoteClass, string $remoteRelation)

Given a relation declared on a remote class, generate a substitute component for the opposite side of the relation.

getManyManyComponents(string $componentName, int|array $id = null)

Returns a many-to-many component, as a ManyManyList.

string|array
hasOne()

Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.

string|array
belongsTo(bool $classOnly = true)

Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and their class name will be returned.

string|array|false
hasMany(bool $classOnly = true)

Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many relationships and their classes will be returned.

array|null
manyManyExtraFields()

Return the many-to-many extra fields specification.

array|null
manyMany()

Return information about a many-to-many component.

array|false
database_extensions(string $class)

This returns an array (if it exists) describing the database extensions that are required, or false if none

getDefaultSearchContext()

Generates a SearchContext to be used for building and processing a generic search form for properties on this object.

scaffoldSearchFields(array $_params = null)

Determine which properties on the DataObject are searchable, and map them to their default {@link FormField} representations. Used for scaffolding a searchform for {@link ModelAdmin}.

scaffoldFormFields(array $_params = null)

Scaffold a simple edit form for all properties on this dataobject, based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.

getCMSFields()

Return a {@link FieldList} of fields that would appropriate for editing this member.

getCMSActions()

need to be overload by solid dataobject, so that the customised actions of that dataobject, including that dataobject's extensions customised actions could be added to the EditForm.

getFrontEndFields(array $params = null)

Used for simple frontend forms without relation editing or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} by default. To customize, either overload this method in your subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.

array
getChangedFields(bool|array $databaseFieldsOnly = false, int $changeLevel = self::CHANGE_STRICT)

Return the fields that have changed since the last write.

bool
isChanged(string $fieldName = null, int $changeLevel = self::CHANGE_STRICT)

Uses {@link getChangedFields()} to determine if fields have been changed since loading them from the database.

$this
setCastedField(string $fieldName, mixed $value)

Set the value of the field, using a casting object.

bool
hasDatabaseField(string $field)

Returns true if the given field exists as a database column

bool
can(string $perm, Member $member = null, array $context = array())

Returns true if the member is allowed to do the given action.

bool|null
extendedCan(string $methodName, Member|int $member, array $context = array())

Process tri-state responses from permission-alterting extensions. The extensions are expected to return one of three values:

bool
canView(Member $member = null)

Users can view their own record.

bool
canEdit(Member $member = null)

Users can edit their own record.

bool
canDelete(Member $member = null)

Users can edit their own record.

bool
canCreate(Member $member = null, array $context = array())

No description

string
debug()

Debugging used by Debug::show()

dbObject(string $fieldName)

Return the DBField object that represents the given field.

mixed
relObject(string $fieldPath)

Traverses to a DBField referenced by relationships between data objects.

mixed
relField(string $fieldName)

Traverses to a field referenced by relationships between data objects, returning the value The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)

string
getReverseAssociation(string $className)

Temporary hack to return an association name, based on class, to get around the mangle of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.

static DataList
get(string $callerClass = null, string|array $filter = "", string|array $sort = "", string $join = "", string|array $limit = null, string $containerClass = DataList::class)

Return all objects matching the filter sub-classes are automatically selected and included

static DataObject|null
get_one(string|null $callerClass = null, string|array $filter = "", bool $cache = true, string $orderBy = "")

Return the first item matching the given query.

flushCache(bool $persistent = true)

Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data.

static 
flush_and_destroy_cache()

Flush the get_one global cache and destroy associated objects.

static 
reset()

Reset all global caches associated with DataObject.

static DataObject
get_by_id(string|int $classOrID, int|bool $idOrCache = null, bool $cache = true)

Return the given element, searching by ID.

string
baseTable()

Get the name of the base table for this object

string
baseClass()

Get the base class for this object

array
getSourceQueryParams()

No description

array
getInheritableQueryParams()

Get list of parameters that should be inherited to relations on this object

setSourceQueryParams($array)

No description

setSourceQueryParam(string $key, string $value)

No description

string
getSourceQueryParam(string $key)

No description

requireTable()

Check the database schema and update it as necessary.

requireDefaultRecords()

Add default records to database. This function is called whenever the database is built, after the database tables have all been created. Overload this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().

array
searchableFields()

Get the default searchable fields for this object, as defined in the $searchable_fields list. If searchable fields are not defined on the data object, uses a default selection of summary fields.

array
fieldLabels(bool $includerelations = true)

No description

string
fieldLabel(string $name)

Get a human-readable label for a single field, see {@link fieldLabels()} for more details.

array
summaryFields()

Get the default summary fields for this object.

array
defaultSearchFilters()

Defines a default list of filters for the search context.

bool
isInDB()

No description

static 
disable_subclass_access()

Temporarily disable subclass access in data object qeur

static 
enable_subclass_access()

No description

array
provideI18nEntities()

Returns the list of provided translations for this object.

getJoin()

If selected through a many_many through relation, this is the instance of the joined record

$this
setJoin(DataObject $object, string $alias = null)

Set joining object

findRelatedObjects(string $source, bool $recursive = true, ArrayList $list = null)

Find objects in the given relationships, merging them into the given list

mergeRelatedObjects(ArrayList $list, mixed $items)

Helper method to merge owned/owning items into a list.

static Member
default_admin() deprecated

Get the default admin record if it exists, or creates it otherwise if enabled

checkPassword(string $password) deprecated

Check if the passed password matches the stored one (if the member is not locked out).

bool
isDefaultAdmin()

Check if this user is the currently configured default admin

bool
canLogin()

Check if this user can login

validateCanLogin(ValidationResult $result = null)

Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid one with error messages to display if the member is locked out.

bool
isLockedOut()

Returns true if this user is locked out

static 
set_password_validator(PasswordValidator $validator = null)

Set a {@link PasswordValidator} object to use to validate member's passwords.

password_validator()

Returns the default {@link PasswordValidator}

isPasswordExpired()

No description

logIn() deprecated

No description

beforeMemberLoggedIn()

Called before a member is logged in via session/cookie/etc

afterMemberLoggedIn()

Called after a member is logged in via session/cookie/etc

regenerateTempID()

Trigger regeneration of TempID.

static bool
logged_in_session_exists() deprecated

Check if the member ID logged in session actually has a database record of the same ID. If there is no logged in user, FALSE is returned anyway.

logOut() deprecated

No description

beforeMemberLoggedOut(HTTPRequest $request = null)

Audit logging hook, called before a member is logged out

afterMemberLoggedOut(HTTPRequest $request = null)

Audit logging hook, called after a member is logged out

string
encryptWithUserSettings(string $string)

Utility for generating secure password hashes for this member.

string
generateAutologinTokenAndStoreHash(int|null $lifetime = null)

Generate an auto login token which can be used to reset the password, at the same time hashing it and storing in the database.

validateAutoLoginToken(string $autologinToken)

Check the token against the member.

static Member
member_from_autologinhash(string $hash, bool $login = false)

Return the member for the auto login hash

static Member
member_from_tempid(string $tempid)

Find a member record with the given TempIDHash value

getMemberFormFields()

Returns the fields for the member form - used in the registration/profile module.

getMemberPasswordField()

Builds "Change / Create Password" field for this member

getValidator()

Returns the {@link RequiredFields} instance for the Member object. This Validator is used when saving a {@link CMSProfileController} or added to any form responsible for saving a users data.

static Member
currentUser() deprecated

Returns the current logged in user

static mixed
actAs(Member|null|int $member, callable $callback)

Temporarily act as the specified user, limited to a $callback, but without logging in as that user.

static int
currentUserID() deprecated

Get the ID of the current logged in user

static string
create_new_password()

Generate a random password, with randomiser to kick in if there's no words file on the filesystem.

onBeforeWrite()

Event handler called before writing to the database.

onAfterWrite()

No description

onAfterDelete()

No description

bool
onChangeGroups(array $ids)

Filter out admin groups to avoid privilege escalation, If any admin groups are requested, deny the whole save operation.

bool
inGroups(array|SS_List $groups, bool $strict = false)

Check if the member is in one of the given groups.

bool
inGroup(int|Group|string $group, bool $strict = false)

Check if the member is in the given group or any parent groups.

addToGroupByCode(string $groupcode, string $title = "")

Adds the member to a group. This will create the group if the given group code does not return a valid group object.

removeFromGroupByCode(string $groupcode)

Removes a member from a group.

static 
set_title_columns(array $columns, string $sep = ' ')

No description

string
getLastName()

Simple proxy method to get the Surname property of the member

static string
get_title_sql()

Return a SQL CONCAT() fragment suitable for a SELECT statement.

string
getName()

Get the complete name of the member

setName(string $name)

Set first- and surname

splitName(string $name)

Alias for {@link setName}

string
getDateFormat()

Return the date format based on the user's chosen locale, falling back to the default format defined by the i18n::config()->get('default_locale') config setting.

getLocale()

Get user locale, falling back to the configured default locale

string
getTimeFormat()

Return the time format based on the user's chosen locale, falling back to the default format defined by the i18n::config()->get('default_locale') config setting.

Member_Groupset
Groups()

Get a "many-to-many" map that holds for all members their group memberships, including any parent groups where membership is implied.

static Map
map_in_groups(mixed $groups = null)

Get a member SQLMap of members in specific groups

static Map
mapInCMSGroups(array $groups = null)

Get a map of all members in the groups given that have CMS permissions

array
memberNotInGroups(array $groupList, array $memberGroups = null)

Get the groups in which the member is NOT in

changePassword(string $password, bool $write = true)

Change password. This will cause rehashing according to the PasswordEncryption property via the onBeforeWrite() method. This method will allow extensions to perform actions and augment the validation result if required before the password is written and can check it after the write also.

registerFailedLogin()

Tell this member that someone made a failed attempt at logging in as them.

registerSuccessfulLogin()

Tell this member that a successful login has been made

string
getHtmlEditorConfigForCMS()

Get the HtmlEditorConfig for this user to be used in the CMS.

LoggedPasswords()

No description

RememberLoginHashes()

No description

Details

mixed __call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

You can add extra methods to a class using {@link Extensions}, {@link Object::createMethod()} or {@link Object::addWrapperMethod()}

Parameters

string $method
array $arguments

Return Value

mixed

Exceptions

BadMethodCallException

bool hasMethod(string $method)

Return TRUE if a method exists on this object

This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions

Parameters

string $method

Return Value

bool

array allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

Parameters

bool $custom

include methods added dynamically at runtime

Return Value

array

Map of method names with lowercase keys

static bool add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.

As an alternative, extensions can be added to a specific class directly in the {@link Object::$extensions} array. See {@link SiteTree::$extensions} for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through {@link singleton()}).

Parameters

string $classOrExtension

Class that should be extended - has to be a subclass of {@link Object}

string $extension

Subclass of {@link Extension} with optional parameters as a string, e.g. "Versioned" or "Translatable('Param')"

Return Value

bool

Flag if the extension was added

See also

http://doc.silverstripe.org/framework/en/trunk/reference/dataextension

static remove_extension(string $extension)

Remove an extension from a class.

Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.

Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any {@link Object} instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through {@link singleton()} to avoid side-effects from stale extension information.

Parameters

string $extension

class name of an {@link Extension} subclass, without parameters

static array get_extensions(string $class = null, bool $includeArgumentString = false)

Parameters

string $class

If omitted, will get extensions for the current class

bool $includeArgumentString

Include the argument string in the return array, FALSE would return array("Versioned"), TRUE returns array("Versioned('Stage','Live')").

Return Value

array

Numeric array of either {@link DataExtension} class names, or eval'ed class name strings with constructor arguments.

static array|null get_extra_config_sources(string $class = null)

Get extra config sources for this class

Parameters

string $class

Name of class. If left null will return for the current class

Return Value

array|null

static bool has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))

Parameters

string $classOrExtension

Class to check extension for, or the extension name to check if the second argument is null.

string $requiredExtension

If the first argument is the parent class, this is the extension to check. If left null, the first parameter will be treated as the extension.

bool $strict

if the extension has to match the required extension and not be a subclass

Return Value

bool

Flag if the extension exists

array invokeWithExtensions(string $method, mixed ...$arguments)

Calls a method if available on both this object and all applied {@link Extensions}, and then attempts to merge all results into an array

Parameters

string $method

the method name to call

mixed ...$arguments

List of arguments

Return Value

array

List of results with nulls filtered out

array extend(string $method, mixed ...$arguments)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.

The extension methods are defined during {@link __construct()} in {@link defineMethods()}.

Parameters

string $method

the name of the method to call on each extension

mixed ...$arguments

Return Value

array

Extension|null getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

Parameters

string $extension

Return Value

Extension|null

bool hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in {@link $extension_instances}. Extension instances are initialized at constructor time, meaning if you use {@link add_extension()} afterwards, the added extension will just be added to new instances of the extended class. Use the static method {@link has_extension()} to check if a class (not an instance) has a specific extension.

Caution: Don't use singleton()->hasExtension() as it will give you inconsistent results based on when the singleton was first accessed.

Parameters

string $extension

Classname of an {@link Extension} subclass without parameters

Return Value

bool

Extension[] getExtensionInstances()

Get all extension instances for this specific object instance.

See {@link get_extensions()} to get all applied extension classes for this class (not the instance).

This method also provides lazy-population of the extension_instances property.

Return Value

Extension[]

Map of {@link DataExtension} instances, keyed by classname.

static Injectable create(array ...$args)

An implementation of the factory method, allows you to create an instance of a class

This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.

This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create('SiteTree'); $list = SiteTree::get();

Parameters

array ...$args

Return Value

Injectable

static Injectable singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).

Parameters

string $class

Optional classname to create, if the called class should not be used

Return Value

Injectable

The singleton instance

static Config_ForClass config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

Return Value

Config_ForClass

mixed stat(string $name) deprecated

deprecated 5.0 Use ->config()->get() instead

Get inherited config value

Parameters

string $name

Return Value

mixed

mixed uninherited(string $name)

Gets the uninherited value for the given config option

Parameters

string $name

Return Value

mixed

$this set_stat(string $name, mixed $value) deprecated

deprecated 5.0 Use ->config()->set() instead

Update the config value for a given property

Parameters

string $name
mixed $value

Return Value

$this

__construct(array|null $record = null, bool $isSingleton = false, array $queryParams = array())

Construct a new DataObject.

Parameters

array|null $record

Used internally for rehydrating an object from database content. Bypasses setters on this class, and hence should not be used for populating data on new records.

bool $isSingleton

This this to true if this is a singleton() object, a stub for calling methods. Singletons don't have their defaults set.

array $queryParams

List of DataQuery params necessary to lazy load, or load related objects.

bool __isset(string $property)

Check if a field exists on this object or its failover.

Note that, unlike the core isset() implementation, this will return true if the property is defined and set to null.

Parameters

string $property

Return Value

bool

mixed __get(string $property)

Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using {@link ViewableData::getField()}, then fall back on a failover object.

Parameters

string $property

Return Value

mixed

__set(string $property, mixed $value)

Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the {@link ViewableData::setField()} method.

Parameters

string $property
mixed $value

setFailover(ViewableData $failover)

Set a failover object to attempt to get data from if it is not present on this object.

Parameters

ViewableData $failover

ViewableData|null getFailover()

Get the current failover object if set

Return Value

ViewableData|null

bool hasField(string $field)

Returns true if the given field exists in a database column on any of the objects tables and optionally look up a dynamic getter with get().

Parameters

string $field

Return Value

bool

mixed getField(string $field)

Gets the value of a field.

Called by {@link __get()} and any getFieldName() methods you might create.

Parameters

string $field

Return Value

mixed

$this setField(string $fieldName, mixed $val)

Set the value of the field Called by {@link __set()} and any setFieldName() methods you might create.

Parameters

string $fieldName

Name of the field

mixed $val

New field value

Return Value

$this

defineMethods()

Adds methods from the extensions.

Called by Object::__construct() once per class.

ViewableData_Customised customise(array|ViewableData $data)

Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance with references to both this and the new custom data.

Note that any fields you specify will take precedence over the fields on this object.

Parameters

array|ViewableData $data

Return Value

ViewableData_Customised

bool exists()

Returns true if this object "exists", i.e., has a sensible value.

The default behaviour for a DataObject is to return true if the object exists in the database, you can override this in subclasses.

Return Value

bool

string __toString()

Return Value

string

the class name

ViewableData getCustomisedObj()

Return Value

ViewableData

setCustomisedObj(ViewableData $object)

Parameters

ViewableData $object

string castingHelper(string $field)

Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.

Parameters

string $field

Return Value

string

Casting helper As a constructor pattern, and may include arguments.

Exceptions

Exception

string castingClass(string $field)

Get the class name a field on this object will be casted to.

Parameters

string $field

Return Value

string

string escapeTypeForField(string $field)

Return the string-format type for the given field.

Parameters

string $field

Return Value

string

'xml'|'raw'

DBHTMLText renderWith(string|array|SSViewer $template, array $customFields = null)

Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter:

  • a template name (e.g. Page)
  • an array of possible template names - the first valid one will be used
  • an SSViewer instance

Parameters

string|array|SSViewer $template

the template to render into

array $customFields

fields to customise() the object with before rendering

Return Value

DBHTMLText

object|DBField obj(string $fieldName, array $arguments = [], bool $cache = false, string $cacheName = null)

Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.

Parameters

string $fieldName
array $arguments
bool $cache

Cache this object

string $cacheName

a custom cache name

Return Value

object|DBField

object|DBField cachedCall(string $field, array $arguments = [], string $identifier = null)

A simple wrapper around {@link ViewableData::obj()} that automatically caches the result so it can be used again without re-running the method.

Parameters

string $field
array $arguments
string $identifier

an optional custom cache identifier

Return Value

object|DBField

bool hasValue(string $field, array $arguments = null, bool $cache = true)

Returns true if the given method/parameter has a value (Uses the DBField::hasValue if the parameter is a database field)

Parameters

string $field
array $arguments
bool $cache

Return Value

bool

string XML_val(string $field, array $arguments = [], bool $cache = false)

Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.

Parameters

string $field
array $arguments
bool $cache

Return Value

string

array getXMLValues(array $fields)

Get an array of XML-escaped values by field name

Parameters

array $fields

an array of field names

Return Value

array

ArrayIterator getIterator()

Return a single-item iterator so you can iterate over the fields of a single record.

This is useful so you can use a single record inside a <% control %> block in a template - and then use to access individual fields on this object.

Return Value

ArrayIterator

array getViewerTemplates(string $suffix = '')

Find appropriate templates for SSViewer to use to render this object

Parameters

string $suffix

Return Value

array

ViewableData Me()

When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.

Return Value

ViewableData

string ThemeDir() deprecated

deprecated 4.0.0:5.0.0 Use $resourcePath or $resourceURL template helpers instead

Return the directory if the current active theme (relative to the site root).

This method is useful for things such as accessing theme images from your template without hardcoding the theme page - e.g. .

This method should only be used when a theme is currently active. However, it will fall over to the current project directory.

Return Value

string

URL to the current theme

string CSSClasses(string $stopAtClass = self::class)

Get part of the current classes ancestry to be used as a CSS class.

This method returns an escaped string of CSS classes representing the current classes ancestry until it hits a stop point - e.g. "Page DataObject ViewableData".

Parameters

string $stopAtClass

the class to stop at (default: ViewableData)

Return Value

string

ViewableData_Debugger Debug()

Return debug information about this object that can be rendered into a template

Return Value

ViewableData_Debugger

static DataObjectSchema getSchema()

Get schema object

Return Value

DataObjectSchema

destroy()

Destroy all of this objects dependant objects and local caches.

You'll need to call this to get the memory of an object that has components or extensions freed.

DataObject duplicate(bool $doWrite = true, array|null|false $relations = null)

Create a duplicate of this node. Can duplicate many_many relations

Parameters

bool $doWrite

Perform a write() operation before returning the object. If this is true, it will create the duplicate in the database.

array|null|false $relations

List of relations to duplicate. Will default to cascade_duplicates if null. Set to 'false' to force none. Set to specific array of names to duplicate to override these. Note: If using versioned, this will additionally failover to owns config.

Return Value

DataObject

A duplicate of this node. The exact type will be the type of this node.

string getObsoleteClassName()

Return obsolete class name, if this is no longer a valid class

Return Value

string

string getClassName()

Gets name of this class

Return Value

string

$this setClassName(string $className)

Set the ClassName attribute. {@link $class} is also updated.

Warning: This will produce an inconsistent record, as the object instance will not automatically switch to the new subclass. Please use {@link newClassInstance()} for this purpose, or destroy and reinstanciate the record.

Parameters

string $className

The new ClassName attribute (a subclass of {@link DataObject})

Return Value

$this

DataObject newClassInstance(string $newClassName)

Create a new instance of a different class from this object's record.

This is useful when dynamically changing the type of an instance. Specifically, it ensures that the instance of the class is a match for the className of the record. Don't set the {@link DataObject->class} or {@link DataObject->ClassName} property manually before calling this method, as it will confuse change detection.

If the new class is different to the original class, defaults are populated again because this will only occur automatically on instantiation of a DataObject if there is no record, or the record has no ID. In this case, we do have an ID but we still need to repopulate the defaults.

Parameters

string $newClassName

The name of the new class

Return Value

DataObject

The new instance of the new class, The exact type will be of the class name provided.

bool isEmpty()

Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).

Return Value

bool

string i18n_pluralise(string $count)

Pluralise this item given a specific count.

E.g. "0 Pages", "1 File", "3 Images"

Parameters

string $count

Return Value

string

string singular_name()

Get the user friendly singular name of this DataObject.

If the name is not defined (by redefining $singular_name in the subclass), this returns the class name.

Return Value

string

User friendly singular name of this DataObject

string i18n_singular_name()

Get the translated user friendly singular name of this DataObject same as singular_name() but runs it through the translating function

Translating string is in the form: $this->class.SINGULARNAME Example: Page.SINGULARNAME

Return Value

string

User friendly translated singular name of this DataObject

string plural_name()

Get the user friendly plural name of this DataObject If the name is not defined (by renaming $plural_name in the subclass), this returns a pluralised version of the class name.

Return Value

string

User friendly plural name of this DataObject

string i18n_plural_name()

Get the translated user friendly plural name of this DataObject Same as plural_name but runs it through the translation function Translation string is in the form: $this->class.PLURALNAME Example: Page.PLURALNAME

Return Value

string

User friendly translated plural name of this DataObject

string getTitle()

Get the complete name of the member, by default in the format ", ".

Falls back to showing either field on its own.

You can overload this getter with {@link set_title_format()} and {@link set_title_sql()}.

Return Value

string

DataObject data()

Returns the associated database record - in this case, the object itself.

This is included so that you can call $dataOrController->data() and get a DataObject all the time.

Return Value

DataObject

Associated database record

array toMap()

Convert this object to a map.

Return Value

array

The data as a map.

array getQueriedDatabaseFields()

Return all currently fetched database fields.

This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields. Obviously, this makes it a lot faster.

Return Value

array

The data as a map.

DataObject update(array $data)

Update a number of fields on this object, given a map of the desired changes.

The field names can be simple names, or you can use a dot syntax to access $has_one relations. For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".

Doesn't write the main object, but if you use the dot syntax, it will write() the related objects that it alters.

When using this method with user supplied data, it's very important to whitelist the allowed keys.

Parameters

array $data

A map of field name to data values to update.

Return Value

DataObject

$this

DataObject castedUpdate(array $data)

Pass changes as a map, and try to get automatic casting for these fields.

Doesn't write to the database. To write the data, use the write() method.

Parameters

array $data

A map of field name to data values to update.

Return Value

DataObject

$this

bool merge(DataObject $rightObj, string $priority = 'right', bool $includeRelations = true, bool $overwriteWithEmpty = false)

Merges data and relations from another object of same class, without conflict resolution. Allows to specify which dataset takes priority in case its not empty.

has_one-relations are just transferred with priority 'right'. has_many and many_many-relations are added regardless of priority.

Caution: has_many/many_many relations are moved rather than duplicated, meaning they are not connected to the merged object any longer. Caution: Just saves updated has_many/many_many relations to the database, doesn't write the updated object itself (just writes the object-properties). Caution: Does not delete the merged object. Caution: Does now overwrite Created date on the original object.

Parameters

DataObject $rightObj
string $priority

left|right Determines who wins in case of a conflict (optional)

bool $includeRelations

Merge any existing relations (optional)

bool $overwriteWithEmpty

Overwrite existing left values with empty right values. Only applicable with $priority='right'. (optional)

Return Value

bool

$this forceChange()

Forces the record to think that all its data has changed.

Doesn't write to the database. Force-change preseved until next write. Existing CHANGE_VALUE or CHANGE_STRICT values are preserved.

Return Value

$this

ValidationResult validate()

Validate this member object.

Return Value

ValidationResult

ValidationResult doValidate()

Public accessor for {see DataObject::validate()}

Return Value

ValidationResult

ArrayList findCascadeDeletes(bool $recursive = true, ArrayList $list = null)

Find all objects that will be cascade deleted if this object is deleted

Notes:

  • If this object is versioned, objects will only be searched in the same stage as the given record.
  • This will only be useful prior to deletion, as post-deletion this record will no longer exist.

Parameters

bool $recursive

True if recursive

ArrayList $list

Optional list to add items to

Return Value

ArrayList

list of objects

DataObject populateDefaults()

Ensure the locale is set to something sensible by default.

Return Value

DataObject

$this

write(bool $showDebug = false, bool $forceInsert = false, bool $forceWrite = false, bool|array $writeComponents = false)

Writes all changes to this object to the database.

  • It will insert a record whenever ID isn't set, otherwise update.
  • All relevant tables will be updated.
  • $this->onBeforeWrite() gets called beforehand.
  • Extensions such as Versioned will ammend the database-write to ensure that a version is saved.

Parameters

bool $showDebug

Show debugging information

bool $forceInsert

Run INSERT command rather than UPDATE, even if record already exists

bool $forceWrite

Write to database even if there are no changes

bool|array $writeComponents

Call write() on all associated component instances which were previously retrieved through {@link getComponent()}, {@link getComponents()} or {@link getManyManyComponents()}. Default to false. The parameter can also be provided in the form of an array: ['recursive' => true, skip => ['Page'=>[1,2,3]]. This avoid infinite loops when one DataObject are components of each other.

Exceptions

ValidationException

Exception that can be caught and handled by the calling function

writeRelations()

Writes cached relation lists to the database, if possible

DataObject writeComponents(bool $recursive = false, array $skip = [])

Write the cached components to the database. Cached components could refer to two different instances of the same record.

Parameters

bool $recursive

Recursively write components

array $skip

List of DataObject references to skip

Return Value

DataObject

$this

delete()

Delete this data object.

$this->onBeforeDelete() gets called. Note that in Versioned objects, both Stage and Live will be deleted.

static delete_by_id(string $className, int $id)

Delete the record with the given ID.

Parameters

string $className

The class name of the record to be deleted

int $id

ID of record to be deleted

array getClassAncestry()

Get the class ancestry, including the current class name.

The ancestry will be returned as an array of class names, where the 0th element will be the class that inherits directly from DataObject, and the last element will be the current class.

Return Value

array

Class ancestry

DataObject getComponent(string $componentName)

Return a unary component object from a one to one relationship, as a DataObject.

If no component is available, an 'empty component' will be returned for non-polymorphic relations, or for polymorphic relations with a class set.

Parameters

string $componentName

Name of the component

Return Value

DataObject

The component object. It's exact type will be that of the component.

Exceptions

Exception

$this setComponent(string $componentName, DataObject|null $item)

Assign an item to the given component

Parameters

string $componentName
DataObject|null $item

Return Value

$this

HasManyList|UnsavedRelationList getComponents(string $componentName, int|array $id = null)

Returns a one-to-many relation as a HasManyList

Parameters

string $componentName

Name of the component

int|array $id

Optional ID(s) for parent of this relation, if not the current record

Return Value

HasManyList|UnsavedRelationList

The components of the one-to-many relationship.

string getRelationClass(string $relationName)

Find the foreign class of a relation on this DataObject, regardless of the relation type.

Parameters

string $relationName

Relation name.

Return Value

string

Class name, or null if not found.

string getRelationType(string $component)

Given a relation name, determine the relation type

Parameters

string $component

Name of component

Return Value

string

has_one, has_many, many_many, belongs_many_many or belongs_to

DataList|DataObject inferReciprocalComponent(string $remoteClass, string $remoteRelation)

Given a relation declared on a remote class, generate a substitute component for the opposite side of the relation.

Notes on behaviour:

  • This can still be used on components that are defined on both sides, but do not need to be.
  • All has_ones on remote class will be treated as local has_many, even if they are belongs_to
  • Polymorphic relationships do not have two natural endpoints (only on one side) and thus attempting to infer them will return nothing.
  • Cannot be used on unsaved objects.

Parameters

string $remoteClass
string $remoteRelation

Return Value

DataList|DataObject

The component, either as a list or single object

Exceptions

BadMethodCallException
InvalidArgumentException

ManyManyList|UnsavedRelationList getManyManyComponents(string $componentName, int|array $id = null)

Returns a many-to-many component, as a ManyManyList.

Parameters

string $componentName

Name of the many-many component

int|array $id

Optional ID for parent of this relation, if not the current record

Return Value

ManyManyList|UnsavedRelationList

The set of components

string|array hasOne()

Return the class of a one-to-one component. If $component is null, return all of the one-to-one components and their classes. If the selected has_one is a polymorphic field then 'DataObject' will be returned for the type.

Return Value

string|array

The class of the one-to-one component, or an array of all one-to-one components and their classes.

string|array belongsTo(bool $classOnly = true)

Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and their class name will be returned.

Parameters

bool $classOnly

If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE.

Return Value

string|array

string|array|false hasMany(bool $classOnly = true)

Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many relationships and their classes will be returned.

Parameters

bool $classOnly

If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE.

Return Value

string|array|false

array|null manyManyExtraFields()

Return the many-to-many extra fields specification.

If you don't specify a component name, it returns all extra fields for all components available.

Return Value

array|null

array|null manyMany()

Return information about a many-to-many component.

The return value is an array of (parentclass, childclass). If $component is null, then all many-many components are returned.

Return Value

array|null

An array of (parentclass, childclass), or an array of all many-many components

See also

DataObjectSchema::manyManyComponent

array|false database_extensions(string $class)

This returns an array (if it exists) describing the database extensions that are required, or false if none

This is experimental, and is currently only a Postgres-specific enhancement.

Parameters

string $class

Return Value

array|false

SearchContext getDefaultSearchContext()

Generates a SearchContext to be used for building and processing a generic search form for properties on this object.

Return Value

SearchContext

FieldList scaffoldSearchFields(array $_params = null)

Determine which properties on the DataObject are searchable, and map them to their default {@link FormField} representations. Used for scaffolding a searchform for {@link ModelAdmin}.

Some additional logic is included for switching field labels, based on how generic or specific the field type is.

Used by {@link SearchContext}.

Parameters

array $_params

'fieldClasses': Associative array of field names as keys and FormField classes as values 'restrictFields': Numeric array of a field name whitelist

Return Value

FieldList

FieldList scaffoldFormFields(array $_params = null)

Scaffold a simple edit form for all properties on this dataobject, based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.

Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.

Parameters

array $_params

Associative array passing through properties to {@link FormScaffolder}.

Return Value

FieldList

FieldList getCMSFields()

Return a {@link FieldList} of fields that would appropriate for editing this member.

Return Value

FieldList

Returns a TabSet for usage within the CMS - don't use for frontend forms.

FieldList getCMSActions()

need to be overload by solid dataobject, so that the customised actions of that dataobject, including that dataobject's extensions customised actions could be added to the EditForm.

Return Value

FieldList

an Empty FieldList(); need to be overload by solid subclass

FieldList getFrontEndFields(array $params = null)

Used for simple frontend forms without relation editing or {@link TabSet} behaviour. Uses {@link scaffoldFormFields()} by default. To customize, either overload this method in your subclass, or extend it by {@link DataExtension->updateFrontEndFields()}.

Parameters

array $params

See {@link scaffoldFormFields()}

Return Value

FieldList

Always returns a simple field collection without TabSet.

array getChangedFields(bool|array $databaseFieldsOnly = false, int $changeLevel = self::CHANGE_STRICT)

Return the fields that have changed since the last write.

The change level affects what the functions defines as "changed":

  • Level CHANGE_STRICT (integer 1) will return strict changes, even !== ones.
  • Level CHANGE_VALUE (integer 2) is more lenient, it will only return real data changes, for example a change from 0 to null would not be included.

Example return: array( 'Title' = array('before' => 'Home', 'after' => 'Home-Changed', 'level' => DataObject::CHANGE_VALUE) )

Parameters

bool|array $databaseFieldsOnly

Filter to determine which fields to return. Set to true to return all database fields, or an array for an explicit filter. false returns all fields.

int $changeLevel

The strictness of what is defined as change. Defaults to strict

Return Value

array

bool isChanged(string $fieldName = null, int $changeLevel = self::CHANGE_STRICT)

Uses {@link getChangedFields()} to determine if fields have been changed since loading them from the database.

Parameters

string $fieldName

Name of the database field to check, will check for any if not given

int $changeLevel

See {@link getChangedFields()}

Return Value

bool

$this setCastedField(string $fieldName, mixed $value)

Set the value of the field, using a casting object.

This is useful when you aren't sure that a date is in SQL format, for example. setCastedField() can also be used, by forms, to set related data. For example, uploaded images can be saved into the Image table.

Parameters

string $fieldName
mixed $value

New field value

Return Value

$this

bool hasDatabaseField(string $field)

Returns true if the given field exists as a database column

Parameters

string $field

Name of the field

Return Value

bool

bool can(string $perm, Member $member = null, array $context = array())

Returns true if the member is allowed to do the given action.

See {@link extendedCan()} for a more versatile tri-state permission control.

Parameters

string $perm

The permission to be checked, such as 'View'.

Member $member

The member whose permissions need checking. Defaults to the currently logged in user.

array $context

Additional $context to pass to extendedCan()

Return Value

bool

True if the the member is allowed to do the given action

bool|null extendedCan(string $methodName, Member|int $member, array $context = array())

Process tri-state responses from permission-alterting extensions. The extensions are expected to return one of three values:

  • false: Disallow this permission, regardless of what other extensions say
    • true: Allow this permission, as long as no other extensions return false
    • NULL: Don't affect the outcome

This method itself returns a tri-state value, and is designed to be used like this:

$extended = $this->extendedCan('canDoSomething', $member); if($extended !== null) return $extended; else return $normalValue;

Parameters

string $methodName

Method on the same object, e.g. {@link canEdit()}

Member|int $member
array $context

Optional context

Return Value

bool|null

bool canView(Member $member = null)

Users can view their own record.

Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions. This is likely to be customized for social sites etc. with a looser permission model.

Parameters

Member $member

Return Value

bool

bool canEdit(Member $member = null)

Users can edit their own record.

Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions

Parameters

Member $member

Return Value

bool

bool canDelete(Member $member = null)

Users can edit their own record.

Otherwise they'll need ADMIN or CMS_ACCESS_SecurityAdmin permissions

Parameters

Member $member

Return Value

bool

bool canCreate(Member $member = null, array $context = array())

Parameters

Member $member
array $context

Additional context-specific data which might affect whether (or where) this object could be created.

Return Value

bool

string debug()

Debugging used by Debug::show()

Return Value

string

HTML data representing this object

DBField dbObject(string $fieldName)

Return the DBField object that represents the given field.

This works similarly to obj() with 2 key differences:

  • it still returns an object even when the field has no value.
  • it only matches fields and not methods
  • it matches foreign keys generated by has_one relationships, eg, "ParentID"

Parameters

string $fieldName

Name of the field

Return Value

DBField

The field as a DBField object

mixed relObject(string $fieldPath)

Traverses to a DBField referenced by relationships between data objects.

The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName).

If a relation is blank, this will return null instead. If a relation name is invalid (e.g. non-relation on a parent) this can throw a LogicException.

Parameters

string $fieldPath

List of paths on this object. All items in this path must be ViewableData implementors

Return Value

mixed

DBField of the field on the object or a DataList instance.

Exceptions

LogicException

If accessing invalid relations

mixed relField(string $fieldName)

Traverses to a field referenced by relationships between data objects, returning the value The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)

Parameters

string $fieldName

string

Return Value

mixed

Will return null on a missing value

string getReverseAssociation(string $className)

Temporary hack to return an association name, based on class, to get around the mangle of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.

Parameters

string $className

Return Value

string

static DataList get(string $callerClass = null, string|array $filter = "", string|array $sort = "", string $join = "", string|array $limit = null, string $containerClass = DataList::class)

Return all objects matching the filter sub-classes are automatically selected and included

Parameters

string $callerClass

The class of objects to be returned

string|array $filter

A filter to be inserted into the WHERE clause. Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.

string|array $sort

A sort expression to be inserted into the ORDER BY clause. If omitted, self::$default_sort will be used.

string $join

Deprecated 3.0 Join clause. Use leftJoin($table, $joinClause) instead.

string|array $limit

A limit expression to be inserted into the LIMIT clause.

string $containerClass

The container class to return the results in.

Return Value

DataList

The objects matching the filter, in the class specified by $containerClass

static DataObject|null get_one(string|null $callerClass = null, string|array $filter = "", bool $cache = true, string $orderBy = "")

Return the first item matching the given query.

All calls to get_one() are cached.

The filter argument supports parameterised queries (see SQLSelect::addWhere() for syntax examples). Because of that (and differently from e.g. DataList::filter()) you need to manually escape the field names: $member = DataObject::get_one('Member', [ '"FirstName"' => 'John' ]);

Parameters

string|null $callerClass

The class of objects to be returned. Defaults to the class that calls the method e.g. MyObject::get_one() will return a MyObject

string|array $filter

A filter to be inserted into the WHERE clause. Supports parameterised queries. See SQLSelect::addWhere() for syntax examples.

bool $cache

Use caching

string $orderBy

A sort expression to be inserted into the ORDER BY clause.

Return Value

DataObject|null

The first item matching the query

DataObject flushCache(bool $persistent = true)

Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data.

Parameters

bool $persistent

When true will also clear persistent data stored in the Cache system. When false will just clear session-local cached data

Return Value

DataObject

$this

static flush_and_destroy_cache()

Flush the get_one global cache and destroy associated objects.

static reset()

Reset all global caches associated with DataObject.

static DataObject get_by_id(string|int $classOrID, int|bool $idOrCache = null, bool $cache = true)

Return the given element, searching by ID.

This can be called either via DataObject::get_by_id(MyClass::class, $id) or MyClass::get_by_id($id)

Parameters

string|int $classOrID

The class of the object to be returned, or id if called on target class

int|bool $idOrCache

The id of the element, or cache if called on target class

bool $cache

See {@link get_one()}

Return Value

DataObject

The element

string baseTable()

Get the name of the base table for this object

Return Value

string

string baseClass()

Get the base class for this object

Return Value

string

array getSourceQueryParams()

Return Value

array

See also

$sourceQueryParams

array getInheritableQueryParams()

Get list of parameters that should be inherited to relations on this object

Return Value

array

setSourceQueryParams($array)

Parameters

$array

See also

$sourceQueryParams

setSourceQueryParam(string $key, string $value)

Parameters

string $key
string $value

See also

$sourceQueryParams

string getSourceQueryParam(string $key)

Parameters

string $key

Return Value

string

See also

$sourceQueryParams

requireTable()

Check the database schema and update it as necessary.

requireDefaultRecords()

Add default records to database. This function is called whenever the database is built, after the database tables have all been created. Overload this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().

array searchableFields()

Get the default searchable fields for this object, as defined in the $searchable_fields list. If searchable fields are not defined on the data object, uses a default selection of summary fields.

Return Value

array

array fieldLabels(bool $includerelations = true)

Parameters

bool $includerelations

a boolean value to indicate if the labels returned include relation fields

Return Value

array

Array of all element labels

string fieldLabel(string $name)

Get a human-readable label for a single field, see {@link fieldLabels()} for more details.

Parameters

string $name

Name of the field

Return Value

string

Label of the field

array summaryFields()

Get the default summary fields for this object.

Return Value

array

array defaultSearchFilters()

Defines a default list of filters for the search context.

If a filter class mapping is defined on the data object, it is constructed here. Otherwise, the default filter specified in {@link DBField} is used.

Return Value

array

bool isInDB()

Return Value

bool

True if the object is in the database

static disable_subclass_access()

Temporarily disable subclass access in data object qeur

static enable_subclass_access()

array provideI18nEntities()

Returns the list of provided translations for this object.

Note: Pluralised forms are always returned in array format.

Example usage: class MyTestClass implements i18nEntityProvider { public function provideI18nEntities() { $entities = []; foreach($this->config()->get('my_static_array') as $key => $value) { $entities["MyTestClass.my_staticarray{$key}"] = $value; } $entities["MyTestClass.PLURALS"] = [ 'one' => 'A test class', 'other' => '{count} test classes', ] return $entities; } }

Example usage in {@link DataObject->provideI18nEntities()}.

You can ask textcollector to add the provided entity to a different module. Simply wrap the returned value for any item in an array with the format: [ 'default' => $defaultValue, 'module' => $module ]

class MyTestClass implements i18nEntityProvider { public function provideI18nEntities() { $entities = [ 'MyOtherModuleClass.MYENTITY' => [ 'default' => $value, 'module' => 'myothermodule', ] ]; } return $entities; }

Return Value

array

Map of keys to default values, which are strings in the default case, and array-form for pluralisations.

DataObject getJoin()

If selected through a many_many through relation, this is the instance of the joined record

Return Value

DataObject

$this setJoin(DataObject $object, string $alias = null)

Set joining object

Parameters

DataObject $object
string $alias

Alias

Return Value

$this

ArrayList findRelatedObjects(string $source, bool $recursive = true, ArrayList $list = null)

Find objects in the given relationships, merging them into the given list

Parameters

string $source

Config property to extract relationships from

bool $recursive

True if recursive

ArrayList $list

If specified, items will be added to this list. If not, a new instance of ArrayList will be constructed and returned

Return Value

ArrayList

The list of related objects

ArrayList mergeRelatedObjects(ArrayList $list, mixed $items)

Helper method to merge owned/owning items into a list.

Items already present in the list will be skipped.

Parameters

ArrayList $list

Items to merge into

mixed $items

List of new items to merge

Return Value

ArrayList

List of all newly added items that did not already exist in $list

static Member default_admin() deprecated

deprecated 4.0.0:5.0.0 Use DefaultAdminService::findOrCreateDefaultAdmin() instead

Get the default admin record if it exists, or creates it otherwise if enabled

Return Value

Member

ValidationResult checkPassword(string $password) deprecated

deprecated 4.0.0:5.0.0 Use Authenticator::checkPassword() instead

Check if the passed password matches the stored one (if the member is not locked out).

Parameters

string $password

Return Value

ValidationResult

bool isDefaultAdmin()

Check if this user is the currently configured default admin

Return Value

bool

bool canLogin()

Check if this user can login

Return Value

bool

ValidationResult validateCanLogin(ValidationResult $result = null)

Returns a valid {@link ValidationResult} if this member can currently log in, or an invalid one with error messages to display if the member is locked out.

You can hook into this with a "canLogIn" method on an attached extension.

Parameters

ValidationResult $result

Optional result to add errors to

Return Value

ValidationResult

bool isLockedOut()

Returns true if this user is locked out

Return Value

bool

static set_password_validator(PasswordValidator $validator = null)

Set a {@link PasswordValidator} object to use to validate member's passwords.

Parameters

PasswordValidator $validator

static PasswordValidator password_validator()

Returns the default {@link PasswordValidator}

Return Value

PasswordValidator

isPasswordExpired()

logIn() deprecated

deprecated 5.0.0 Use Security::setCurrentUser() or IdentityStore::logIn()

beforeMemberLoggedIn()

Called before a member is logged in via session/cookie/etc

afterMemberLoggedIn()

Called after a member is logged in via session/cookie/etc

regenerateTempID()

Trigger regeneration of TempID.

This should be performed any time the user presents their normal identification (normally Email) and is successfully authenticated.

static bool logged_in_session_exists() deprecated

deprecated Not needed anymore, as it returns Security::getCurrentUser();

Check if the member ID logged in session actually has a database record of the same ID. If there is no logged in user, FALSE is returned anyway.

Return Value

bool

TRUE record found FALSE no record found

logOut() deprecated

deprecated Use Security::setCurrentUser(null) or an IdentityStore Logs this member out.

beforeMemberLoggedOut(HTTPRequest $request = null)

Audit logging hook, called before a member is logged out

Parameters

HTTPRequest $request

afterMemberLoggedOut(HTTPRequest $request = null)

Audit logging hook, called after a member is logged out

Parameters

HTTPRequest $request

string encryptWithUserSettings(string $string)

Utility for generating secure password hashes for this member.

Parameters

string $string

Return Value

string

Exceptions

PasswordEncryptor_NotFoundException

string generateAutologinTokenAndStoreHash(int|null $lifetime = null)

Generate an auto login token which can be used to reset the password, at the same time hashing it and storing in the database.

Parameters

int|null $lifetime

DEPRECATED: The lifetime of the auto login hash in days. Overrides the Member.auto_login_token_lifetime config value

Return Value

string

Token that should be passed to the client (but NOT persisted).

validateAutoLoginToken(string $autologinToken)

Check the token against the member.

Parameters

string $autologinToken

static Member member_from_autologinhash(string $hash, bool $login = false)

Return the member for the auto login hash

Parameters

string $hash

The hash key

bool $login

Should the member be logged in?

Return Value

Member

the matching member, if valid

static Member member_from_tempid(string $tempid)

Find a member record with the given TempIDHash value

Parameters

string $tempid

Return Value

Member

FieldList getMemberFormFields()

Returns the fields for the member form - used in the registration/profile module.

It should return fields that are editable by the admin and the logged-in user.

Return Value

FieldList

Returns a {@link FieldList} containing the fields for the member form.

ConfirmedPasswordField getMemberPasswordField()

Builds "Change / Create Password" field for this member

Return Value

ConfirmedPasswordField

Member_Validator getValidator()

Returns the {@link RequiredFields} instance for the Member object. This Validator is used when saving a {@link CMSProfileController} or added to any form responsible for saving a users data.

To customize the required fields, add a {@link DataExtension} to member calling the updateValidator() method.

Return Value

Member_Validator

static Member currentUser() deprecated

deprecated 5.0.0 use Security::getCurrentUser()

Returns the current logged in user

Return Value

Member

static mixed actAs(Member|null|int $member, callable $callback)

Temporarily act as the specified user, limited to a $callback, but without logging in as that user.

E.g. Member::actAs(Security::findAnAdministrator(), function() { $record->write(); });

Parameters

Member|null|int $member

Member or member ID to log in as. Set to null or 0 to act as a logged out user.

callable $callback

Return Value

mixed

Result of $callback

static int currentUserID() deprecated

deprecated 5.0.0 use Security::getCurrentUser()

Get the ID of the current logged in user

Return Value

int

Returns the ID of the current logged in user or 0.

static string create_new_password()

Generate a random password, with randomiser to kick in if there's no words file on the filesystem.

Return Value

string

Returns a random password.

onBeforeWrite()

Event handler called before writing to the database.

onAfterWrite()

onAfterDelete()

bool onChangeGroups(array $ids)

Filter out admin groups to avoid privilege escalation, If any admin groups are requested, deny the whole save operation.

Parameters

array $ids

Database IDs of Group records

Return Value

bool

True if the change can be accepted

bool inGroups(array|SS_List $groups, bool $strict = false)

Check if the member is in one of the given groups.

Parameters

array|SS_List $groups

Collection of {@link Group} DataObjects to check

bool $strict

Only determine direct group membership if set to true (Default: false)

Return Value

bool

Returns TRUE if the member is in one of the given groups, otherwise FALSE.

bool inGroup(int|Group|string $group, bool $strict = false)

Check if the member is in the given group or any parent groups.

Parameters

int|Group|string $group

Group instance, Group Code or ID

bool $strict

Only determine direct group membership if set to TRUE (Default: FALSE)

Return Value

bool

Returns TRUE if the member is in the given group, otherwise FALSE.

addToGroupByCode(string $groupcode, string $title = "")

Adds the member to a group. This will create the group if the given group code does not return a valid group object.

Parameters

string $groupcode
string $title

Title of the group

removeFromGroupByCode(string $groupcode)

Removes a member from a group.

Parameters

string $groupcode

static set_title_columns(array $columns, string $sep = ' ')

Parameters

array $columns

Column names on the Member record to show in {@link getTitle()}.

string $sep

Separator

string getLastName()

Simple proxy method to get the Surname property of the member

Return Value

string

static string get_title_sql()

Return a SQL CONCAT() fragment suitable for a SELECT statement.

Useful for custom queries which assume a certain member title format.

Return Value

string

SQL

string getName()

Get the complete name of the member

Return Value

string

Returns the first- and surname of the member.

setName(string $name)

Set first- and surname

This method assumes that the last part of the name is the surname, e.g. A B C will result in firstname A B and surname C

Parameters

string $name

The name

splitName(string $name)

Alias for {@link setName}

Parameters

string $name

The name

See also

setName()

string getDateFormat()

Return the date format based on the user's chosen locale, falling back to the default format defined by the i18n::config()->get('default_locale') config setting.

Return Value

string

ISO date format

getLocale()

Get user locale, falling back to the configured default locale

string getTimeFormat()

Return the time format based on the user's chosen locale, falling back to the default format defined by the i18n::config()->get('default_locale') config setting.

Return Value

string

ISO date format

Member_Groupset Groups()

Get a "many-to-many" map that holds for all members their group memberships, including any parent groups where membership is implied.

Use {@link DirectGroups()} to only retrieve the group relations without inheritance.

Return Value

Member_Groupset

static Map map_in_groups(mixed $groups = null)

Get a member SQLMap of members in specific groups

If no $groups is passed, all members will be returned

Parameters

mixed $groups
  • takes a SS_List, an array or a single Group.ID

Return Value

Map

Returns an Map that returns all Member data.

static Map mapInCMSGroups(array $groups = null)

Get a map of all members in the groups given that have CMS permissions

If no groups are passed, all groups with CMS permissions will be used.

Parameters

array $groups

Groups to consider or NULL to use all groups with CMS permissions.

Return Value

Map

Returns a map of all members in the groups given that have CMS permissions.

array memberNotInGroups(array $groupList, array $memberGroups = null)

Get the groups in which the member is NOT in

When passed an array of groups, and a component set of groups, this function will return the array of groups the member is NOT in.

Parameters

array $groupList

An array of group code names.

array $memberGroups

A component set of groups (if set to NULL, $this->groups() will be used)

Return Value

array

Groups in which the member is NOT in.

ValidationResult changePassword(string $password, bool $write = true)

Change password. This will cause rehashing according to the PasswordEncryption property via the onBeforeWrite() method. This method will allow extensions to perform actions and augment the validation result if required before the password is written and can check it after the write also.

onBeforeWrite() will encrypt the password prior to writing.

Parameters

string $password

Cleartext password

bool $write

Whether to write the member afterwards

Return Value

ValidationResult

registerFailedLogin()

Tell this member that someone made a failed attempt at logging in as them.

This can be used to lock the user out temporarily if too many failed attempts are made.

registerSuccessfulLogin()

Tell this member that a successful login has been made

string getHtmlEditorConfigForCMS()

Get the HtmlEditorConfig for this user to be used in the CMS.

This is set by the group. If multiple configurations are set, the one with the highest priority wins.

Return Value

string

HasManyList LoggedPasswords()

Return Value

HasManyList

HasManyList RememberLoginHashes()

Return Value

HasManyList