DataObject
class DataObject extends ViewableData implements DataObjectInterface, i18nEntityProvider (View source)
A single database record & abstract class for the data-access-model.
Extensions
See Extension} and {@link DataExtension.
Permission Control
Object-level access control by Permission. Permission codes are arbitrary strings which can be selected on a group-by-group basis.
class Article extends DataObject implements PermissionProvider {
static $api_access = true;
function canView($member = false) {
return Permission::check('ARTICLE_VIEW');
}
function canEdit($member = false) {
return Permission::check('ARTICLE_EDIT');
}
function canDelete() {
return Permission::check('ARTICLE_DELETE');
}
function canCreate() {
return Permission::check('ARTICLE_CREATE');
}
function providePermissions() {
return array(
'ARTICLE_VIEW' => 'Read an article object',
'ARTICLE_EDIT' => 'Edit an article object',
'ARTICLE_DELETE' => 'Delete an article object',
'ARTICLE_CREATE' => 'Create an article object',
);
}
}
Object-level access control by Group membership:
class Article extends DataObject {
static $api_access = true;
function canView($member = false) {
if(!$member) $member = Member::currentUser();
return $member->inGroup('Subscribers');
}
function canEdit($member = false) {
if(!$member) $member = Member::currentUser();
return $member->inGroup('Editors');
}
// ...
}
If any public method on this class is prefixed with an underscore, the results are cached in memory through cachedCall().
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
public | string | $class | from SS_Object | |
protected | array | $extension_instances | from SS_Object | |
protected | $beforeExtendCallbacks | List of callbacks to call prior to extensions having extend called on them, each grouped by methodName. |
from SS_Object | |
protected | $afterExtendCallbacks | List of callbacks to call after extensions having extend called on them, each grouped by methodName. |
from SS_Object | |
protected | ViewableData | $failover | A failover object to attempt to get data from if it is not present on this object. |
from ViewableData |
protected | ViewableData | $customisedObject | from ViewableData | |
public | bool | $destroyed | True if this DataObject has been destroyed. |
|
protected | $model | The DataModel from this this object comes |
||
protected | array | $record | Data stored in this objects database record. An array indexed by fieldname. |
|
protected | array | $original | The database record (in the same format as $record), before any changes. |
|
protected | bool | $brokenOnDelete | Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete() |
|
protected | bool | $brokenOnWrite | Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite() |
|
public static | $cache_has_own_table | Static caches used by relevant functions. |
||
protected static | $_cache_db | |||
protected static | $_cache_get_one | |||
protected static | $_cache_get_class_ancestry | |||
protected static | $_cache_composite_fields | |||
protected static | $_cache_is_composite_field | |||
protected static | $_cache_custom_database_fields | |||
protected static | $_cache_field_labels | |||
protected | $components | Non-static relationship cache, indexed by component name. |
||
protected | $unsavedRelations | Non-static cache of has_many and many_many relations that can't be written until this object is saved. |
||
protected | array | $sourceQueryParams | ||
public static | $allowed_actions | Provides a list of allowed methods that can be called via RESTful api. |
Methods
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
An implementation of the factory method, allows you to create an instance of a class
Creates a class instance by the "singleton" design pattern.
Create an object from a string representation. It treats it as a PHP constructor without the 'new' keyword. It also manages to construct the object without the use of eval().
Parses a class-spec, such as "Versioned('Stage','Live')", as passed to create_from_string().
Similar to Object::create(), except that classes are only overloaded if you set the $strong parameter to TRUE when using Object::useCustomClass()
This class allows you to overload classes with other classes when they are constructed using the factory method Object::create()
If a class has been overloaded, get the class name it has been overloaded with - otherwise return the class name
Get the value of a static property of a class, even in that property is declared protected (but not private), without any inheritance, merging or parent lookup if it doesn't exist on the given class.
Return TRUE if a class has a specified extension.
Add an extension to a specific class.
No description
Construct a new DataObject.
Attemps to locate and call a method dynamically added to a class at runtime if a default cannot be located
Return the names of all the methods available on this object
Add all the methods from an object property (which is an Extension) to this object.
Add all the methods from an object property (which is an Extension) to this object.
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
Add an extra method using raw PHP code passed as a string
Check if this class is an instance of a specific class, or has that class as one of its parents
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
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
Get an extension instance attached to this object by name.
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Get all extension instances for this specific object instance.
Cache the results of an instance method in this object to a file, or if it is already cache return the cached results
Clears the cache for the given cacheToFile call
Loads a cache from the filesystem if a valid on is present and within the specified lifetime
Save a piece of cached data to the file system
Strip a file name of special characters so it is suitable for use as a cache file name
Converts a field spec into an object creator. For example: "Int" becomes "new Int($fieldName);" and "Varchar(50)" becomes "new Varchar($fieldName, 50);".
Convert a field schema (e.g. "Varchar(50)") into a casting object creator array that contains both a className and castingHelper constructor code. See castingObjectCreator for more information about the constructor.
Check if a field exists on this object or its failover.
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 ViewableData::getField(), then fall back on a failover object.
Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the ViewableData::setField() method.
Set a failover object to attempt to get data from if it is not present on this object.
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
Set the value of the field Called by __set() and any setFieldName() methods you might create.
Method to facilitate deprecation of underscore-prefixed methods automatically being cached.
Merge some arbitrary data in with this object. This method returns a ViewableData_Customised instance with references to both this and the new custom data.
Get the class a field on this object would be casted to, as well as the casting helper for casting a field to an object (see ViewableData::castingHelper() for information on casting helpers).
Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object.
Get the class name a field on this object will be casted to
Return the string-format type for the given field.
Save the casting cache for this object (including data from any failovers) into a variable
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
Generate the cache name for a field
Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.
A simple wrapper around ViewableData::obj() that automatically caches the result so it can be used again without re-running the method.
Returns true if the given method/parameter has a value (Uses the DBField::hasValue if the parameter is a database field)
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.
Return the value of the field without any escaping being applied.
Return the value of a field in an SQL-safe format.
Return the value of a field in a JavaScript-save format.
Return the value of a field escaped suitable to be inserted into an XML node attribute.
Get an array of XML-escaped values by field name
Return a single-item iterator so you can iterate over the fields of a single record.
When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.
Return the directory if the current active theme (relative to the site root).
Get part of the current classes ancestry to be used as a CSS class.
Return debug information about this object that can be rendered into a template
Set whether DataObjects should be validated before they are written.
Clear all cached classname specs. It's necessary to clear all cached subclassed names for any classes if a new class manifest is generated.
Determines the specification for the ClassName field for the given class
Return the complete map of fields on this object, including "Created", "LastEdited" and "ClassName".
Get all database columns explicitly defined on a class in DataObject::$db and DataObject::$has_one}. Resolves instances of {@link CompositeDBField into the actual database fields, rather than the name of the field which might not equate a database column.
Returns the field class if the given db field on the class is a composite field.
Returns a list of all the composite if the given db field on the class is a composite field.
Copies the many_many and belongs_many_many relations from one object to another instance of the name of object The destinationObject must be written to the database already and have an ID. Writing is performed automatically when adding the new relations.
Set the ClassName attribute. $class is also updated.
Create a new instance of a different class from this object's record.
Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).
Get the translated user friendly singular name of this DataObject same as singular_name() but runs it through the translating function
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.
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
Standard implementation of a title/label for a specific record. Tries to find properties 'Title' or 'Name', and falls back to the 'ID'. Useful to provide user-friendly identification of a record, e.g. in errormessages or UI-selections.
Update a number of fields on this object, given a map of the desired changes.
Pass changes as a map, and try to get automatic casting for these fields.
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.
Detects and updates all changes made to this object
Writes a subset of changes for a specific table to the given manipulation
Ensures that a blank base record exists with the basic fixed fields for this dataobject
Generate and write the database manipulation for all changed fields
Writes all changes to this object to the database.
Write the cached components to the database. Cached components could refer to two different instances of the same record.
Return a component object from a one to one relationship, as a DataObject.
Returns a one-to-many relation as a HasManyList
No description
Find the foreign class of a relation on this DataObject, regardless of the relation type.
Tries to find the database key on another object that is used to store a relationship to this class. If no join field can be found it defaults to 'ParentID'.
Returns a many-to-many component, as a ManyManyList.
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.
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.
Return data for a specific belongs_to component.
Return all of the database fields defined in self::$db and all the parent classes.
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.
Return data for a specific has_many component.
Return the many-to-many extra fields specification.
Return the many-to-many extra fields specification for a specific component.
Return information about a many-to-many component.
Return information about a specific many_many component. Returns a numeric array of: array(
This returns an array (if it exists) describing the database extensions that are required, or false if none
Generates a SearchContext to be used for building and processing a generic search form for properties on this object.
Determine which properties on the DataObject are searchable, and map them to their default FormField representations. Used for scaffolding a searchform for ModelAdmin.
Scaffold a simple edit form for all properties on this dataobject, based on default FormField} mapping in {@link DBField::scaffoldFormField().
Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields being called on extensions
Centerpiece of every data administration interface in Silverstripe, which returns a FieldList} suitable for a {@link Form object.
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.
Used for simple frontend forms without relation editing or TabSet} behaviour. Uses {@link scaffoldFormFields() by default. To customize, either overload this method in your subclass, or extend it by DataExtension->updateFrontEndFields().
Loads all the stub fields that an initial lazy load didn't load fully.
Return the fields that have changed.
Uses getChangedFields() to determine if fields have been changed since loading them from the database.
Returns true if the given field exists as a database column
Returns the field type of the given field, if it belongs to this class, and not a parent.
Returns the field type of the given field, if it belongs to this class, and not a parent.
Returns true if given class has its own table. Uses the rules for whether the table should exist rather than actually looking in the database.
Process tri-state responses from permission-alterting extensions. The extensions are expected to return one of three values:
Return the DBField object that represents the given field.
Traverses to a DBField referenced by relationships between data objects.
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)
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.
Return all objects matching the filter sub-classes are automatically selected and included
Return the first item matching the given query.
Flush the cached results for all relations (has_one, has_many, many_many) Also clears any cached aggregate data.
Flush the get_one global cache and destroy associated objects.
Return the given element, searching by ID
Parses a specified column into a sort field and direction
Validate that the configured relations for this class use the correct syntaxes
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().
Returns fields bu traversing the class heirachy in a bottom-up direction.
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.
Get any user defined searchable fields labels that exist. Allows overriding of default field names in the form interface actually presented to the user.
Get a human-readable label for a single field, see fieldLabels() for more details.
Collect all static properties on the object which contain natural language, and need to be translated.
Details
static Config_ForClass|null
config()
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
protected
beforeExtending(string $method, callable $callback)
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
protected
afterExtending(string $method, callable $callback)
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
static SS_Object
create()
An implementation of the factory method, allows you to create an instance of a class
This method first for strong class overloads (singletons & DB interaction), then custom class overloads. If an overload is found, an instance of this is returned rather than the original class. To overload a class, use Object::useCustomClass()
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();
static SS_Object
singleton()
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).
static
create_from_string($classSpec, $firstArg = null)
Create an object from a string representation. It treats it as a PHP constructor without the 'new' keyword. It also manages to construct the object without the use of eval().
Construction itself is done with Object::create(), so that Object::useCustomClass() calls are respected.
Object::create_from_string("Versioned('Stage','Live')")
will return the result of
Versioned::create('Stage', 'Live);
It is designed for simple, clonable objects. The first time this method is called for a given string it is cached, and clones of that object are returned.
If you pass the $firstArg argument, this will be prepended to the constructor arguments. It's impossible to pass null as the firstArg argument.
Object::create_from_string("Varchar(50)", "MyField")
will return the result of
Vachar::create('MyField', '50');
Arguments are always strings, although this is a quirk of the current implementation rather than something that can be relied upon.
static
parse_class_spec($classSpec)
Parses a class-spec, such as "Versioned('Stage','Live')", as passed to create_from_string().
Returns a 2-elemnent array, with classname and arguments
static SS_Object
strong_create()
Similar to Object::create(), except that classes are only overloaded if you set the $strong parameter to TRUE when using Object::useCustomClass()
static
useCustomClass(string $oldClass, string $newClass, bool $strong = false)
This class allows you to overload classes with other classes when they are constructed using the factory method Object::create()
static string
getCustomClass(string $class)
If a class has been overloaded, get the class name it has been overloaded with - otherwise return the class name
static any
static_lookup($class, $name, null $default = null)
Get the value of a static property of a class, even in that property is declared protected (but not private), without any inheritance, merging or parent lookup if it doesn't exist on the given class.
static
get_static($class, $name, $uncached = false)
deprecated
deprecated
No description
static
set_static($class, $name, $value)
deprecated
deprecated
No description
static
uninherited_static($class, $name, $uncached = false)
deprecated
deprecated
No description
static
combined_static($class, $name, $ceiling = false)
deprecated
deprecated
No description
static
addStaticVars($class, $properties, $replace = false)
deprecated
deprecated
No description
static
add_static_var($class, $name, $value, $replace = false)
deprecated
deprecated
No description
static
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))
static
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 Object::$extensions array. See 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 singleton()).
static
remove_extension(string $extension)
Remove an extension from a class.
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 Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.
static array
get_extensions(string $class, bool $includeArgumentString = false)
No description
static
get_extra_config_sources($class = null)
No description
__construct(array|null $record = null, bool $isSingleton = false, $model = null)
Construct a new DataObject.
mixed
__call(string $method, array $arguments)
Attemps 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 Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()
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
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
defineMethods()
Adds methods from the extensions.
Called by Object::__construct() once per class.
protected array
findMethodsFromExtension(object $extension)
No description
protected
addMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property (which is an Extension) to this object.
protected
removeMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property (which is an Extension) to this object.
protected
addWrapperMethod(string $method, string $wrap)
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
protected
createMethod(string $method, string $code)
Add an extra method using raw PHP code passed as a string
stat($name, $uncached = false)
No description
set_stat($name, $value)
No description
uninherited($name)
No description
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.
string
parentClass()
No description
bool
is_a(string $class)
Check if this class is an instance of a specific class, or has that class as one of its parents
string
__toString()
No description
mixed
invokeWithExtensions(string $method, mixed $argument = null)
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
array
extend(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)
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 __construct()} in {@link defineMethods().
Extension
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 $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Caution: Don't use singleton(
array
getExtensionInstances()
Get all extension instances for this specific object instance.
See get_extensions() to get all applied extension classes for this class (not the instance).
mixed
cacheToFile(string $method, int $lifetime = 3600, string $ID = false, array $arguments = array())
Cache the results of an instance method in this object to a file, or if it is already cache return the cached results
clearCache($method, $ID = false, $arguments = array())
Clears the cache for the given cacheToFile call
protected mixed
loadCache(string $cache, int $lifetime = 3600)
Loads a cache from the filesystem if a valid on is present and within the specified lifetime
protected
saveCache(string $cache, mixed $data)
Save a piece of cached data to the file system
protected string
sanitiseCachename(string $name)
Strip a file name of special characters so it is suitable for use as a cache file name
static string
castingObjectCreator(string $fieldSchema)
Converts a field spec into an object creator. For example: "Int" becomes "new Int($fieldName);" and "Varchar(50)" becomes "new Varchar($fieldName, 50);".
static array
castingObjectCreatorPair(string $fieldSchema)
Convert a field schema (e.g. "Varchar(50)") into a casting object creator array that contains both a className and castingHelper constructor code. See castingObjectCreator for more information about the constructor.
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 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 ViewableData::setField() method.
setFailover(ViewableData $failover)
Set a failover object to attempt to get data from if it is not present on this object.
ViewableData|null
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.
Called by __get() and any getFieldName() methods you might create.
setField(string $fieldName, mixed $val)
Set the value of the field Called by __set() and any setFieldName() methods you might create.
unknown
deprecatedCachedCall($method, $args = null, string $identifier = null)
Method to facilitate deprecation of underscore-prefixed methods automatically being cached.
ViewableData_Customised
customise(array|ViewableData $data)
Merge some arbitrary data in with this object. This method returns a 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.
ViewableData
getCustomisedObj()
No description
setCustomisedObj(ViewableData $object)
No description
array
castingHelperPair(string $field)
Get the class a field on this object would be casted to, as well as the casting helper for casting a field to an object (see ViewableData::castingHelper() for information on casting helpers).
The returned array contains two keys:
- className: the class the field would be casted to (e.g. "Varchar")
- castingHelper: the casting helper for casting the field (e.g. "return new Varchar($fieldName)")
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.
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.
buildCastingCache(reference $cache)
Save the casting cache for this object (including data from any failovers) into a variable
HTMLText
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
protected
objCacheName(string $fieldName, array $arguments)
Generate the cache name for a field
protected mixed
objCacheGet(string $key)
Get a cached value from the field cache
protected
objCacheSet(string $key, mixed $value)
Store a value in the field cache
obj(string $fieldName, array $arguments = null, bool $forceReturnedObject = true, 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.
cachedCall(string $field, array $arguments = null, string $identifier = null)
A simple wrapper around 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)
XML_val($field, $arguments = null, $cache = false)
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.
RAW_val($field, $arguments = null, $cache = true)
Return the value of the field without any escaping being applied.
SQL_val($field, $arguments = null, $cache = true)
Return the value of a field in an SQL-safe format.
JS_val($field, $arguments = null, $cache = true)
Return the value of a field in a JavaScript-save format.
ATT_val($field, $arguments = null, $cache = true)
Return the value of a field escaped suitable to be inserted into an XML node attribute.
array
getXMLValues($fields)
Get an array of XML-escaped values by field name
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.
ViewableData
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(string $subtheme = false)
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.
string
CSSClasses(string $stopAtClass = 'ViewableData')
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".
ViewableData_Debugger
Debug()
Return debug information about this object that can be rendered into a template
static bool
get_validation_enabled()
deprecated
deprecated
Returns when validation on DataObjects is enabled.
static
set_validation_enabled($enable)
deprecated
deprecated
Set whether DataObjects should be validated before they are written.
Caution: Validation can contain safeguards against invalid/malicious data, and check permission levels (e.g. on Group). Therefore it is recommended to only disable validation for very specific use cases.
static
clear_classname_spec_cache()
Clear all cached classname specs. It's necessary to clear all cached subclassed names for any classes if a new class manifest is generated.
static string
get_classname_spec(string $class, bool $queryDB = true)
Determines the specification for the ClassName field for the given class
static array
database_fields(string $class, bool $queryDB = true)
Return the complete map of fields on this object, including "Created", "LastEdited" and "ClassName".
See custom_database_fields() for a getter that excludes these "base fields".
static array
custom_database_fields(string $class)
Get all database columns explicitly defined on a class in DataObject::$db and DataObject::$has_one}. Resolves instances of {@link CompositeDBField into the actual database fields, rather than the name of the field which might not equate a database column.
Does not include "base fields" like "ID", "ClassName", "Created", "LastEdited", see database_fields().
static string
is_composite_field(string $class, string $name, bool $aggregated = true)
Returns the field class if the given db field on the class is a composite field.
Will check all applicable ancestor classes and aggregate results.
static
composite_fields($class, $aggregated = true)
Returns a list of all the composite if the given db field on the class is a composite field.
Will check all applicable ancestor classes and aggregate results.
DataObject
setDataModel(DataModel $model)
Set the DataModel
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($doWrite = true)
Create a duplicate of this node.
Note: now also duplicates relations.
protected DataObject
duplicateManyManyRelations($sourceObject, $destinationObject)
Copies the many_many and belongs_many_many relations from one object to another instance of the name of object The destinationObject must be written to the database already and have an ID. Writing is performed automatically when adding the new relations.
getObsoleteClassName()
No description
getClassName()
No description
DataObject
setClassName(string $className)
Set the ClassName attribute. $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 newClassInstance() for this purpose, or destroy and reinstanciate the record.
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 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.
bool
isEmpty()
Returns TRUE if all values (other than "ID") are considered empty (by weak boolean comparison).
Only checks for fields listed in custom_database_fields()
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.
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
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()
Standard implementation of a title/label for a specific record. Tries to find properties 'Title' or 'Name', and falls back to the 'ID'. Useful to provide user-friendly identification of a record, e.g. in errormessages or UI-selections.
Overload this method to have a more specialized implementation, e.g. for an Address record this could be:
function getTitle() {
return "{$this->StreetNumber} {$this->StreetName} {$this->City}";
}
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.
array
toMap()
Convert this object to 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.
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".
update() doesn't write the main object, but if you use the dot syntax, it will write() the related objects that it alters.
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.
bool
merge($rightObj, $priority = 'right', $includeRelations = true, $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.
$this
forceChange()
Forces the record to think that all its data has changed.
Doesn't write to the database. Only sets fields as changed if they are not already marked as changed.
protected ValidationResult
validate()
Validate the current object.
By default, there is no validation - objects are always valid! However, you can overload this method in your DataObject sub-classes to specify custom validation, or use the hook through DataExtension.
Invalid objects won't be able to be written - a warning will be thrown and no write will occur. onBeforeWrite() and onAfterWrite() won't get called either.
It is expected that you call validate() in your own application to test that an object is valid before attempting a write, and respond appropriately if it isn't.
ValidationResult
doValidate()
Public accessor for {DataObject::validate()}
protected
onBeforeWrite()
Event handler called before writing to the database.
You can overload this to clean up or otherwise process data before writing it to the database. Don't forget to call parent::onBeforeWrite(), though!
This called after $this->validate(), so you can be sure that your data is valid.
protected
onAfterWrite()
Event handler called after writing to the database.
You can overload this to act upon changes made to the data after it is written. $this->changed will have a record database. Don't forget to call parent::onAfterWrite(), though!
protected
onBeforeDelete()
Event handler called before deleting from the database.
You can overload this to clean up or otherwise process data before delete this record. Don't forget to call parent::onBeforeDelete(), though!
protected
onAfterDelete()
No description
DataObject
populateDefaults()
Load the default values in from the self::$defaults array.
Will traverse the defaults of the current class and all its parent classes. Called by the constructor when creating new records.
protected ValidationException
validateWrite()
Determine validation of this object prior to write
protected
preWrite()
Prepare an object prior to write
protected bool
updateChanges(bool $forceChanges = false)
Detects and updates all changes made to this object
protected
prepareManipulationTable(string $baseTable, string $now, bool $isNewRecord, array $manipulation, string $class)
Writes a subset of changes for a specific table to the given manipulation
protected
writeBaseRecord(string $baseTable, string $now)
Ensures that a blank base record exists with the basic fixed fields for this dataobject
Does nothing if an ID is already assigned for this record
protected
writeManipulation(string $baseTable, string $now, bool $isNewRecord)
Generate and write the database manipulation for all changed fields
write(bool $showDebug = false, bool $forceInsert = false, bool $forceWrite = false, bool $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.
writeRelations()
Writes cached relation lists to the database, if possible
DataObject
writeComponents($recursive = false)
Write the cached components to the database. Cached components could refer to two different instances of the same record.
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.
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.
DataObject
getComponent(string $componentName)
Return a 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.
HasManyList
getComponents(string $componentName, string|null $filter = null, string|null|array $sort = null, string $join = null, string|null|array $limit = null)
Returns a one-to-many relation as a HasManyList
getComponentsQuery($componentName, $filter = "", $sort = "", $join = "", $limit = "")
deprecated
deprecated
No description
string
getRelationClass($relationName)
Find the foreign class of a relation on this DataObject, regardless of the relation type.
string
getRemoteJoinField(string $component, string $type = 'has_many', bool $polymorphic = false)
Tries to find the database key on another object that is used to store a relationship to this class. If no join field can be found it defaults to 'ParentID'.
If the remote field is polymorphic then $polymorphic is set to true, and the return value is in the form 'Relation' instead of 'RelationID', referencing the composite DBField.
ManyManyList
getManyManyComponents(string $componentName, $filter = null, $sort = null, $join = null, $limit = null)
Returns a many-to-many component, as a ManyManyList.
array|null
has_one(string $component = null)
deprecated
deprecated
No description
string|array
hasOne(string $component = null)
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|null
hasOneComponent(string $component)
Return data for a specific has_one component.
array|null
belongs_to(string $component = null, bool $classOnly = true)
deprecated
deprecated
No description
string|array
belongsTo(string $component = null, 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|false
belongsToComponent(string $component, bool $classOnly = true)
Return data for a specific belongs_to component.
array
db(string $fieldName = null)
Return all of the database fields defined in self::$db and all the parent classes.
Doesn't include any fields specified by self::$has_one. Use $this->hasOne() to get these fields
array|null
has_many(string $component = null, bool $classOnly = true)
deprecated
deprecated
No description
string|array|false
hasMany(string $component = null, 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.
string|false
hasManyComponent(string $component, bool $classOnly = true)
Return data for a specific has_many component.
array
many_many_extraFields(string $component = null)
deprecated
deprecated
No description
array|null
manyManyExtraFields(string $component = null)
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.
array|null
manyManyExtraFieldsForComponent(string $component)
Return the many-to-many extra fields specification for a specific component.
array|null
many_many(string $component = null)
deprecated
deprecated
No description
array|null
manyMany(string $component = null)
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.
array|null
manyManyComponent(string $component)
Return information about a specific many_many component. Returns a numeric array of: array(
array
database_extensions($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.
SearchContext
getDefaultSearchContext()
Generates a SearchContext to be used for building and processing a generic search form for properties on this object.
FieldList
scaffoldSearchFields(array $_params = null)
Determine which properties on the DataObject are searchable, and map them to their default FormField representations. Used for scaffolding a searchform for ModelAdmin.
Some additional logic is included for switching field labels, based on how generic or specific the field type is.
Used by SearchContext.
FieldList
scaffoldFormFields(array $_params = null)
Scaffold a simple edit form for all properties on this dataobject, based on default FormField} mapping in {@link DBField::scaffoldFormField().
Field labels/titles will be auto generated from DataObject::fieldLabels().
protected
beforeUpdateCMSFields(callable $callback)
Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields being called on extensions
FieldList
getCMSFields()
Centerpiece of every data administration interface in Silverstripe, which returns a FieldList} suitable for a {@link Form object.
If not overloaded, we're using scaffoldFormFields() to automatically generate this set. To customize, overload this method in a subclass or extended onto it by using DataExtension->updateCMSFields().
class MyCustomClass extends DataObject {
static $db = array('CustomProperty'=>'Boolean');
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
return $fields;
}
}
an
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.
FieldList
getFrontEndFields(array $params = null)
Used for simple frontend forms without relation editing or TabSet} behaviour. Uses {@link scaffoldFormFields() by default. To customize, either overload this method in your subclass, or extend it by DataExtension->updateFrontEndFields().
protected bool
loadLazyFields(string $tableClass = null)
Loads all the stub fields that an initial lazy load didn't load fully.
array
getChangedFields(bool $databaseFieldsOnly = false, int $changeLevel = self::CHANGE_STRICT)
Return the fields that have changed.
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)
)
bool
isChanged(string $fieldName = null, int $changeLevel = self::CHANGE_STRICT)
Uses getChangedFields() to determine if fields have been changed since loading them from the database.
setCastedField($fieldName, $val)
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.
bool
hasDatabaseField(string $field)
Returns true if the given field exists as a database column
string
hasOwnTableDatabaseField(string $field)
Returns the field type of the given field, if it belongs to this class, and not a parent.
Note that the field type will not include constructor arguments in round brackets, only the classname.
static string
has_own_table_database_field(string $class, string $field)
Returns the field type of the given field, if it belongs to this class, and not a parent.
Note that the field type will not include constructor arguments in round brackets, only the classname.
static bool
has_own_table(string $dataClass)
Returns true if given class has its own table. Uses the rules for whether the table should exist rather than actually looking in the database.
bool
can(string $perm, Member $member = null)
Returns true if the member is allowed to do the given action.
See extendedCan() for a more versatile tri-state permission control.
bool|null
extendedCan(string $methodName, Member|int $member)
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;
bool
canView(Member $member = null)
No description
bool
canEdit(Member $member = null)
No description
bool
canDelete(Member $member = null)
No description
bool
canCreate(Member $member = null)
No description
string
debug()
Debugging used by Debug::show()
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"
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).
string
relField($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($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')
Return all objects matching the filter sub-classes are automatically selected and included
Aggregate($class = null)
deprecated
deprecated
No description
RelationshipAggregate($relationship)
deprecated
deprecated
No description
static DataObject
get_one(string $callerClass, string|array $filter = "", bool $cache = true, string $orderby = "")
Return the first item matching the given query.
All calls to get_one() are cached.
DataObject
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 $callerClass, int $id, bool $cache = true)
Return the given element, searching by ID
baseTable()
Get the name of the base table for this object
array
getSourceQueryParams()
No description
setSourceQueryParams($array)
No description
setSourceQueryParam($key, $value)
No description
mixed
getSourceQueryParam($key)
No description
databaseIndexes()
Return the database indexes on this table.
This array is indexed by the name of the field with the index, and the value is the type of index.
protected array
parseSortColumn(string $column)
Parses a specified column into a sort field and direction
requireTable()
Check the database schema and update it as necessary.
protected
validateModelDefinitions()
Validate that the configured relations for this class use the correct syntaxes
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().
inheritedDatabaseFields()
Returns fields bu traversing the class heirachy in a bottom-up direction.
Needed to avoid getCMSFields being empty when customDatabaseFields overlooks the inheritance chain of the $db array, where a child data object has no $db array, but still needs to know the properties of its parent. This should be merged into databaseFields or customDatabaseFields.
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|string
fieldLabels(bool $includerelations = true)
Get any user defined searchable fields labels that exist. Allows overriding of default field names in the form interface actually presented to the user.
The reason for keeping this separate from searchable_fields, which would be a logical place for this functionality, is to avoid bloating and complicating the configuration array. Currently much of this system is based on sensible defaults, and this property would generally only be set in the case of more complex relationships between data object being required in the search interface.
Generates labels based on name of the field itself, if no static property self::field_labels exists.
string
fieldLabel(string $name)
Get a human-readable label for a single field, see 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.
If a filter class mapping is defined on the data object, it is constructed here. Otherwise, the default filter specified in DBField is used.
bool
isInDB()
No description
static
disable_subclass_access()
Temporarily disable subclass access in data object qeur
static
enable_subclass_access()
No description
array
provideI18nEntities()
Collect all static properties on the object which contain natural language, and need to be translated.
The full entity name is composed from the class name and a custom identifier.