File
class File extends DataObject implements AssetContainer, Thumbnail, CMSPreviewable, PermissionProvider, Resettable mixin Hierarchy mixin Versioned mixin RecursivePublishable mixin InheritedPermissionsExtension (View source)
This class handles the representation of a file on the filesystem within the framework.
Most of the methods also handle the Folder subclass.
Note: The files are stored in the assets/ directory, but SilverStripe looks at the db object to gather information about a file such as URL It then uses this for all processing functions (like image manipulation).
Security
Caution: It is recommended to disable any script execution in the "assets/" directory in the webserver configuration, to reduce the risk of exploits. See http://doc.silverstripe.org/secure-development#filesystem
Asset storage
As asset storage is configured separately to any File DataObject records, this class does not make any assumptions about how these records are saved. They could be on a local filesystem, remote filesystem, or a virtual record container (such as in local memory).
The File dataobject simply represents an externally facing view of shared resources within this asset store.
Internally individual files are referenced by a"Filename" parameter, which represents a File, extension, and is optionally prefixed by a list of custom directories. This path is root-agnostic, so it does not automatically have a direct url mapping (even to the site's base directory).
Additionally, individual files may have several versions distinguished by sha1 hash, of which a File DataObject can point to a single one. Files can also be distinguished by variants, which may be resized images or format-shifted documents.
Properties
- "Title": Optional title of the file (for display purposes only). Defaults to "Name". Note that the Title field of Folder (subclass of File) is linked to Name, so Name and Title will always be the same. -"File": Physical asset backing this DB record. This is a composite DB field with its own list of properties. {\SilverStripe\Assets\Storage\DBFile} for more information
- "Content": Typically unused, but handy for a textual representation of files, e.g. for fulltext indexing of PDF documents.
- "ParentID": Points to a Folder record. Should be in sync with "Filename". A ParentID=0 value points to the "assets/" folder, not the webroot. -"ShowInSearch": True if this file is searchable
Traits
Provides image manipulation functionality.
This trait can be applied to a ViewableData class to add the logic to render attributes in an SS template.
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 |
CREATE_OBJECT |
Value for 2nd argument to constructor, indicating that a new record is being created
Setters will be called on fields passed, and defaults will be populated |
CREATE_SINGLETON |
Value for 2nd argument to constructor, indicating that a record is a singleton representing the whole type,
e.g. to call requireTable() in dev/build
Defaults will not be populated and data passed will be ignored |
CREATE_HYDRATED |
Value for 2nd argument to constructor, indicating that a record is being hydrated from the database
Setter methods are not called, and population via private static $defaults will not occur. |
CREATE_MEMORY_HYDRATED |
Value for 2nd argument to constructor, indicating that a record is being hydrated from memory. This can be used
to initialised a record that doesn't yet have an ID. Setter methods are not called, and population via private
static $defaults will not occur. |
EDIT_ALL |
Permission for edit all files |
Config options
extensions | |||
unextendable_classes | array | Classes that cannot be extended |
from Extensible |
casting | |||
default_cast | string | The default object to cast scalar fields to if casting information is not specified, and casting to an object is required. |
from ViewableData |
casting_cache | array | from ViewableData | |
singular_name | string | ||
plural_name | |||
api_access | from DataObject | ||
default_classname | string | Allows specification of a default value for the ClassName field. |
from DataObject |
validation_enabled | bool | Should dataobjects be validated before they are written? |
from DataObject |
fixed_fields | array | Base fields which are not defined in static $db |
from DataObject |
table_name | |||
scaffold_cms_fields_settings | array | Settings used by the FormScaffolder that scaffolds fields for getCMSFields() |
from DataObject |
cascade_deletes | array | List of relations that should be cascade deleted, similar to |
from DataObject |
cascade_duplicates | array | List of relations that should be cascade duplicate. |
from DataObject |
subclass_access | from DataObject | ||
db | |||
create_table_options | array | Specify custom options for a CREATE TABLE call. |
from DataObject |
indexes | |||
defaults | |||
default_records | array | 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 |
has_one | |||
belongs_to | array | A meta-relationship that allows you to define the reverse side of a DataObject::$has_one. |
from DataObject |
has_many | |||
many_many | array | many-many relationship definitions. |
from DataObject |
many_many_extraFields | array | Extra fields to include on the connecting many-many table. |
from DataObject |
belongs_many_many | array | The inverse side of a many-many relationship. |
from DataObject |
default_sort | |||
searchable_fields | array | Default list of fields that can be scaffolded by the ModelAdmin search interface. |
from DataObject |
general_search_field_name | string | Name of the field which is used as a stand-in for searching across all searchable fields. |
from DataObject |
general_search_field_filter | string | The search filter to use when searching with the general search field. |
from DataObject |
general_search_split_terms | bool | If true, the search phrase is split into individual terms, and checks all searchable fields for each search term. |
from DataObject |
field_labels | array | User defined labels for searchable_fields, used to override default display in the search form. |
from DataObject |
summary_fields | array | Provides a default list of fields to be used by a 'summary' view of this object. |
from DataObject |
force_resample | bool | Force all images to resample in all cases Off by default, as this can be resource intensive to apply to multiple images simultaneously. |
from ImageManipulation |
strip_thumbnail_width | int | from ImageManipulation | |
strip_thumbnail_height | int | from ImageManipulation | |
cms_thumbnail_width | int | The width of an image thumbnail in the CMS. |
from ImageManipulation |
cms_thumbnail_height | int | The height of an image thumbnail in the CMS. |
from ImageManipulation |
asset_preview_width | int | The width of an image preview in the Asset section |
from ImageManipulation |
asset_preview_height | int | The height of an image preview in the Asset section |
from ImageManipulation |
resample_images | bool | Control whether images in the admin will be resampled |
|
non_live_permissions | array | Anyone with CMS access can view draft files |
|
owned_by | |||
allowed_extensions | array | ||
app_categories | array | ||
class_for_file_extension | Map of file extensions to class type |
||
apply_restrictions_to_admin | bool | ||
update_filesystem | bool | ||
file_types | string[] | A list of file extensions and a description of what type of file they represent |
Properties
protected static | array | $extra_methods | Custom method sources |
from CustomMethods |
protected | array | $extra_method_registers | Name of methods to invoke by defineMethods for this instance |
from CustomMethods |
protected static | array | $built_in_methods | Non-custom public methods. |
from CustomMethods |
protected | Extension[] | $extension_instances | from Extensible | |
protected | callable[][] | $beforeExtendCallbacks | List of callbacks to call prior to extensions having extend called on them, each grouped by methodName. |
from Extensible |
protected | callable[][] | $afterExtendCallbacks | List of callbacks to call after extensions having extend called on them, each grouped by methodName. |
from Extensible |
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 | |
protected | array | $record | Data stored in this objects database record. An array indexed by fieldname. |
from DataObject |
protected | DataObject | $joinRecord | If selected through a many_many through relation, this is the instance of the through record |
from DataObject |
protected | array | $original | The database record (in the same format as $record), before any changes. |
from DataObject |
protected | bool | $brokenOnDelete | Used by onBeforeDelete() to ensure child classes call parent::onBeforeDelete() |
from DataObject |
protected | bool | $brokenOnWrite | Used by onBeforeWrite() to ensure child classes call parent::onBeforeWrite() |
from DataObject |
protected static | array | $_cache_get_one | Static caches used by relevant functions. |
from DataObject |
protected static | array | $_cache_field_labels | Cache of field labels |
from DataObject |
protected | DataObject[] | $components | Non-static relationship cache, indexed by component name. |
from DataObject |
protected | UnsavedRelationList[] | $unsavedRelations | Non-static cache of has_many and many_many relations that can't be written until this object is saved. |
from DataObject |
protected | array | $sourceQueryParams | from DataObject | |
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 | Title of the file |
||
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 | |
protected | array | $attributes | List of attributes to render on the frontend |
from AttributesHTML |
protected | Image_Backend | $imageBackend | from ImageManipulation | |
protected | bool | $allowGeneration | If image resizes are allowed |
from ImageManipulation |
string | $Name | Basename of the file |
||
string | $Filename | Full filename of this file |
||
DBFile | $File | asset stored behind this File record |
||
string | $Content | |||
string | $ShowInSearch | Boolean that indicates if file is shown in search. Doesn't apply to Folders |
||
int | $ParentID | ID of parent File/Folder |
||
int | $OwnerID | ID of Member who owns the file |
Methods
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
Adds any methods from Extension instances attached to this object.
Register an callback to invoke that defines extra methods
Return TRUE if a method exists on this object
Determines if a custom method with this name is defined.
Get meta-data details on a named method
Return the names of all the methods available on this object
Get all public built in methods for this class
Find all methods on the given object.
Add all the methods from an object property.
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 callback as a method.
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.
Adds any methods from Extension instances attached to this object.
Add an extension to a specific class.
No description
Get extra config sources for this class
Return TRUE if a class has a specified extension.
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.
An implementation of the factory method, allows you to create an instance of a class
Creates a class instance by the "singleton" design pattern.
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
Gets the uninherited value for the given config option
Construct a new DataObject.
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.
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.
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.
Get the class name a field on this object will be casted to.
Return the string-format type for the given field.
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
Store a value in the field cache
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.
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.
Find appropriate templates for SSViewer to use to render this object
When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.
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
Create a duplicate of this node. Can duplicate many_many relations
Copies the given relations from this object to the destination
Duplicates a single many_many relation from one object to another.
Duplicates a single many_many relation from one object to another.
Duplicates a single has_one relation from one object to another.
Duplicates a single belongs_to relation from one object to another.
Return obsolete class name, if this is no longer a valid class
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).
Pluralise this item given a specific count.
Get the user friendly singular name of this DataObject.
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.
Returns the associated database record - in this case, the object itself.
Return all currently fetched database fields.
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.
Forces the record to think that all its data has changed.
Find all objects that will be cascade deleted if this object is deleted
Load the default values in from the DataObject::$defaults array.
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.
Delete the record with the given ID.
Get the class ancestry, including the current class name.
Return a unary component object from a one to one relationship, as a DataObject.
No description
Returns a one-to-many relation as a HasManyList
Find the foreign class of a relation on this DataObject, regardless of the relation type.
Given a relation name, determine the relation type
Given a relation declared on a remote class, generate a substitute component for the opposite side of the relation.
Returns a many-to-many component, as a ManyManyList.
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.
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 the many-to-many extra fields specification.
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.
Name of the field which is used as a stand-in for searching across all searchable fields.
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().
Scaffold a form field for selecting records of this model type in a has_one relation.
Scaffold a form field for selecting records of this model type in a has_many relation.
Scaffold a form field for selecting records of this model type in a many_many relation.
Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields being called on extensions
Allows user code to hook into DataObject::getCMSFields after updateCMSFields being called on extensions
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.
When extending this class and overriding this method, you will need to instantiate the CompositeValidator by calling parent::getCMSCompositeValidator(). This will ensure that the appropriate extension point is also invoked.
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 since the last write.
Uses getChangedFields() to determine if fields have been changed since loading them from the database.
Set the value of the field, using a casting object.
Returns true if the given field exists as a database column
Returns true if the member is allowed to do the given action.
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.
Get list of parameters that should be inherited to relations on this object
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().
Invoked after every database build is complete (including after table creation and default record population).
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.
Defines a default list of filters for the search context.
Returns the list of provided translations for this object.
If selected through a many_many through relation, this is the instance of the joined record
Find objects in the given relationships, merging them into the given list
Helper method to merge owned/owning items into a list.
Generate a unique key for data object the unique key uses the DataObject::getUniqueKeyComponents() extension point so unique key modifiers such as versioned or fluent are covered i.e. same data object in different stages or different locales will produce different unique key
Merge single object into a list, but ensures that existing objects are not re-added.
Retrieve the value of an HTML attribute
Get the default attributes when rendering this object.
Allows customization through an 'updateAttributes' hook on the base class.
Custom attributes to process. Falls back to getAttributes().
Set whether image resizes are allowed
Return clone of self which promises to only return existing thumbnails
Fit image to specified dimensions and fill leftover space with a solid colour (default white). Use in templates with $Pad.
Update the url to point to a resampled version if forcing
Generate a resized copy of this image with the given width & height.
Scale image proportionally to fit within the specified bounds
Proportionally scale down this image if it is wider or taller than the specified dimensions.
Scale image proportionally by width. Use in templates with $ScaleWidth.
Proportionally scale down this image if it is wider than the specified width.
Scale image proportionally by height. Use in templates with $ScaleHeight.
Proportionally scale down this image if it is taller than the specified height.
Crop image on X axis if it exceeds specified width. Retain height.
Crop image on Y axis if it exceeds specified height. Retain width.
Crop this image to the aspect ratio defined by the specified width and height, then scale down the image to those dimensions if it exceeds them.
Resize and crop image to fill specified dimensions.
Default thumbnail generation for Images
Thubnail generation for all file types.
Get URL to thumbnail of the given size.
Convert the file to another format if there's a registered converter that can handle it.
Return the relative URL of an icon for the file type, based on the appCategory() value.
Determine if this image is of the specified size
Determine if this image is of the specified width
Determine if this image is of the specified width
Wrapper for manipulate() that creates a variant file with a different extension than the original file.
Wrapper for manipulate that passes in and stores Image_Backend objects instead of tuples
Generate a new DBFile instance using the given callback if it hasn't been created yet, or return the existing one if it has.
Name a variant based on a format with arbitrary parameters
Validate a width or size is valid and casts it to integer
Check if the File has a CanViewType set or inherited at "LoggedInUsers or above"
For a category or list of categories, get the list of file extensions
Generate a readable title, dashes and underscores replaced by whitespace, and any file extensions removed.
This will check if the parent record and/or name do not match the name on the underlying DBFile record, and if so, copy this file to the new location, and update the record to point to this new file.
Collate selected descendants of this page.
Get an asset renamer for the given filename.
Get expected value of Filename tuple value. Will be used to trigger a file move on draft stage.
Gets the extension of a filepath or filename, by stripping away everything before the last "dot".
Given an extension, determine the icon that should be used
Return the type of file for the given extension on the current file name.
Formats a file size (eg: (int)42 becomes string '42 bytes')
Maps a File subclass to a specific extension.
Assign a local file to the backend.
Assign a stream to the backend
Assign a set of data to the backend
Get the back-link tracking objects that link to this file via HTML fields
Joins one or more segments together to build a Filename identifier.
Publicly expose the file (and all variants) identified by the given filename and hash {AssetStore::publish}
Protect a file (and all variants) from public access, identified by the given filename and hash.
Ensures that access to the specified protected file is granted for the current user.
Determine the preview link, if available, for this object.
Return a map of permission codes to add to the dropdown shown in the Security section of the CMS.
Get the list of globally allowed file extensions for file uploads.
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 Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()
protected
defineMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
protected
registerExtraMethodCallback(string $name, callable $callback)
Register an callback to invoke that defines extra methods
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
protected bool
hasCustomMethod($method)
Determines if a custom method with this name is defined.
protected array
getExtraMethodConfig(string $method)
Get meta-data details on a named method
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
static protected array
findBuiltInMethods(string|object $class = null)
Get all public built in methods for this class
protected array
findMethodsFrom(object $object)
Find all methods on the given object.
protected
addMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property.
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
addCallbackMethod(string $method, callable $callback)
Add callback as a method.
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.
protected
defineExtensionMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
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 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.
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 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 = 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.
This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))
array
invokeWithExtensions(string $method, mixed ...$arguments)
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 ...$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 __construct()} in {@link defineMethods().
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 $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(
Extension[]
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).
This method also provides lazy-population of the extension_instances property.
static Injectable
create(mixed ...$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::class); $list = SiteTree::get();
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).
static Config_ForClass
config()
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
mixed
uninherited(string $name)
Gets the uninherited value for the given config option
__construct(array $record = [], int|bool $creationType = DataObject::CREATE_OBJECT, array $queryParams = [])
Construct a new DataObject.
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.
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.
$this
setField(string $fieldName, mixed $val)
Set the value of the field Called by __set() and any setFieldName() methods you might create.
mixed
getDynamicData(string $field)
No description
ViewableData
setDynamicData(string $field, mixed $value)
No description
bool
hasDynamicData(string $field)
No description
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.
bool
exists()
A file only exists if the file_exists() and is in the DB as a record
Use $file->isInDB() to only check for a DB record Use $file->File->exists() to only check if the asset exists
string
__toString()
No description
ViewableData
getCustomisedObj()
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.
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
protected string
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 $this
objCacheSet(string $key, mixed $value)
Store a value in the field cache
protected $this
objCacheClear()
Clear object cache
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 $fieldName, array $arguments = [], 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)
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
Traversable
getIterator()
deprecated
deprecated
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.
array
getViewerTemplates(string $suffix = '')
Find appropriate templates for SSViewer to use to render 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
CSSClasses(string $stopAtClass = ViewableData::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".
ViewableData_Debugger
Debug()
Return debug information about this object that can be rendered into a template
static DataObjectSchema
getSchema()
Get schema object
destroy()
Destroy all of this objects dependent 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 $relations = null)
Create a duplicate of this node. Can duplicate many_many relations
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.
protected
duplicateRelations(DataObject $sourceObject, DataObject $destinationObject, array $relations)
Copies the given relations from this object to the destination
protected
duplicateManyManyRelation(DataObject $sourceObject, DataObject $destinationObject, string $relation)
Duplicates a single many_many relation from one object to another.
protected
duplicateHasManyRelation(DataObject $sourceObject, DataObject $destinationObject, string $relation)
Duplicates a single many_many relation from one object to another.
protected
duplicateHasOneRelation(DataObject $sourceObject, DataObject $destinationObject, string $relation)
Duplicates a single has_one relation from one object to another.
Note: Child object will be force written.
protected
duplicateBelongsToRelation(DataObject $sourceObject, DataObject $destinationObject, string $relation)
Duplicates a single belongs_to relation from one object to another.
Note: This will force a write on both parent / child objects.
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. $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.
T
newClassInstance(T> $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).
string
i18n_pluralise(string $count)
Pluralise this item given a specific count.
E.g. "0 Pages", "1 File", "3 Images"
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.
Note that it has the following quirks:
- custom getters, including those that adjust the result of database fields, won't be executed
- NULL values won't be returned.
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".
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.
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(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.
$this
forceChange()
Forces the record to think that all its data has changed.
Doesn't write to the database. Force-change preserved until next write. Existing CHANGE_VALUE or CHANGE_STRICT values are preserved.
ValidationResult
validate()
No description
protected
onBeforeWrite()
Make sure the file has a name
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!
DataObject>
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.
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()
Update link tracking on delete
DataObject
populateDefaults()
Load the default values in from the DataObject::$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|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 amend the database-write to ensure that a version is saved.
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.
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 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.
$this
setComponent(string $componentName, DataObject|null $item)
Assign an item to the given component
void
setEagerLoadedData(string $eagerLoadRelation, DataObject $eagerLoadedData)
No description
HasManyList|UnsavedRelationList
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
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.
ManyManyList|UnsavedRelationList
getManyManyComponents(string $componentName, int|array $id = null)
Returns a many-to-many component, as a ManyManyList.
array
hasOne()
Return the class of a all has_one relations.
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.
If you don't specify a component name, it returns all extra fields for all components available.
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.
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.
SearchContext<static>
getDefaultSearchContext()
Generates a SearchContext to be used for building and processing a generic search form for properties on this object.
string
getGeneralSearchFieldName()
Name of the field which is used as a stand-in for searching across all searchable fields.
If this is a blank string, general search functionality is disabled and the general search field falls back to using the first field in the searchable fields array.
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().
FormField
scaffoldFormFieldForHasOne(string $fieldName, string|null $fieldTitle, string $relationName, DataObject $ownerRecord)
Scaffold a form field for selecting records of this model type in a has_one relation.
FormField
scaffoldFormFieldForHasMany(string $relationName, string|null $fieldTitle, DataObject $ownerRecord, bool $includeInOwnTab)
Scaffold a form field for selecting records of this model type in a has_many relation.
FormField
scaffoldFormFieldForManyMany(string $relationName, string|null $fieldTitle, DataObject $ownerRecord, bool $includeInOwnTab)
Scaffold a form field for selecting records of this model type in a many_many relation.
protected
beforeUpdateCMSFields(callable $callback)
Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields being called on extensions
protected
afterUpdateCMSFields(callable $callback)
Allows user code to hook into DataObject::getCMSFields after updateCMSFields being called on extensions
FieldList
getCMSFields()
List of basic content editable file fields.
Note: These fields no longer affect the edit form in asset-admin. To add fields to the file edit form in asset-admin, you will need to add an extension to FileFormFactory and use the updateFormFields() hook.
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.
CompositeValidator
getCMSCompositeValidator()
When extending this class and overriding this method, you will need to instantiate the CompositeValidator by calling parent::getCMSCompositeValidator(). This will ensure that the appropriate extension point is also invoked.
You can also update the CompositeValidator by creating an Extension and implementing the updateCMSCompositeValidator(CompositeValidator $compositeValidator) method.
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 $class = null)
Loads all the stub fields that an initial lazy load didn't load fully.
array
getChangedFields(bool|array $databaseFieldsOnly = false, int $changeLevel = DataObject::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)
)
bool
isChanged(string $fieldName = null, int $changeLevel = DataObject::CHANGE_STRICT)
Uses 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.
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
bool
can(string $perm, Member $member = null, array $context = [])
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, array $context = [])
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)
Check if this file can be modified
bool
canDelete(Member $member = null)
Check if this file can be deleted
bool
canCreate(Member $member = null, array $context = [])
Check if a file can be created
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).
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.
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<static>
get(string $callerClass = null, string|array $filter = "", string|array|null $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|array|null $sort = "")
Return the first item matching the given query.
The object returned is cached, unlike DataObject::get()->first() DataList::first() and DataObject::get()->last() DataList::last()
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' ]);
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|null
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)
The object returned is cached, unlike DataObject::get()->byID() DataList::byID()
string
baseTable()
Get the name of the base table for this object
DataObject>
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 $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().
onAfterBuild()
Invoked after every database build is complete (including after table creation and default record population).
See DatabaseAdmin::doBuild() for context.
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)
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 DataObject::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()
deprecated
deprecated
Temporarily disable subclass access in data object qeur
static
enable_subclass_access()
deprecated
deprecated
No description
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_static_array_{$key}"] = $value;
}
$entities["MyTestClass.PLURALS"] = [
'one' => 'A test class',
'other' => '{count} test classes',
]
return $entities;
}
}
Example usage in 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;
}
DataObject
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
DataObject>
findRelatedObjects(string $source, bool $recursive = true, ArrayList $list = null)
Find objects in the given relationships, merging them into the given list
DataObject>
mergeRelatedObjects(ArrayList $list, DataObject>|DataObject|null $items)
Helper method to merge owned/owning items into a list.
Items already present in the list will be skipped.
string
getUniqueKey()
Generate a unique key for data object the unique key uses the DataObject::getUniqueKeyComponents() extension point so unique key modifiers such as versioned or fluent are covered i.e. same data object in different stages or different locales will produce different unique key
recommended use:
- when you need unique key for caching purposes
- when you need unique id on the front end (for example JavaScript needs to target specific element)
protected
mergeRelatedObject(ArrayList $list, ArrayList $added, DataObject $item)
Merge single object into a list, but ensures that existing objects are not re-added.
$this
setAttribute($name, $value)
Set an HTML attribute
mixed|null
getAttribute(string $name)
Retrieve the value of an HTML attribute
abstract protected array
getDefaultAttributes()
Get the default attributes when rendering this object.
Called by getAttributes()
array
getAttributes()
Allows customization through an 'updateAttributes' hook on the base class.
Existing attributes are passed in as the first argument and can be manipulated, but any attributes added through a subclass implementation won't be included.
string
getAttributesHTML(array $attributes = null)
Custom attributes to process. Falls back to getAttributes().
If at least one argument is passed as a string, all arguments act as excludes, by name.
$this
setAllowGeneration(bool $allow)
Set whether image resizes are allowed
bool
getAllowGeneration()
Check if resizes are allowed
DBFile
existingOnly()
Return clone of self which promises to only return existing thumbnails
string
getString()
No description
resource
getStream()
No description
string
getURL(bool $grant = false)
Gets the URL of this file
string
getAbsoluteURL()
Gets the URL of this file
array|null
getMetaData()
Get metadata for this file
string
getMimeType()
Get mime type
int
getAbsoluteSize()
Return file size in bytes.
string
getFilename()
Get value of filename
string
getHash()
Get value of hash
string
getVariant()
Get value of variant
bool
getIsImage()
Determine if a valid non-empty image exists behind this asset
AssetContainer
Pad(int $width, int $height, string $backgroundColor = 'FFFFFF', int $transparencyPercent = 0)
Fit image to specified dimensions and fill leftover space with a solid colour (default white). Use in templates with $Pad.
AssetContainer
Resampled()
Forces the image to be resampled, if possible
updateURL(string $url)
Update the url to point to a resampled version if forcing
AssetContainer
ResizedImage(int $width, int $height)
Generate a resized copy of this image with the given width & height.
This can be used in templates with $ResizedImage but should be avoided, as it's the only image manipulation function which can skew an image.
AssetContainer
Fit(int $width, int $height)
Scale image proportionally to fit within the specified bounds
AssetContainer
FitMax(int $width, int $height)
Proportionally scale down this image if it is wider or taller than the specified dimensions.
Similar to Fit but without up-sampling. Use in templates with $FitMax.
AssetContainer
ScaleWidth(int $width)
Scale image proportionally by width. Use in templates with $ScaleWidth.
AssetContainer
ScaleMaxWidth(int $width)
Proportionally scale down this image if it is wider than the specified width.
Similar to ScaleWidth but without up-sampling. Use in templates with $ScaleMaxWidth.
AssetContainer
ScaleHeight(int $height)
Scale image proportionally by height. Use in templates with $ScaleHeight.
AssetContainer
ScaleMaxHeight(int $height)
Proportionally scale down this image if it is taller than the specified height.
Similar to ScaleHeight but without up-sampling. Use in templates with $ScaleMaxHeight.
AssetContainer
CropWidth(int $width)
Crop image on X axis if it exceeds specified width. Retain height.
Use in templates with $CropWidth. Example: $Image.ScaleHeight(100).$CropWidth(100)
AssetContainer
CropHeight(int $height)
Crop image on Y axis if it exceeds specified height. Retain width.
Use in templates with $CropHeight. Example: $Image.ScaleWidth(100).CropHeight(100)
AssetContainer
FillMax(int $width, int $height)
Crop this image to the aspect ratio defined by the specified width and height, then scale down the image to those dimensions if it exceeds them.
Similar to Fill but without up-sampling. Use in templates with $FillMax.
AssetContainer
Fill(int $width, int $height)
Resize and crop image to fill specified dimensions.
Use in templates with $Fill
AssetContainer
Quality(int $quality)
Set the quality of the resampled image
DBFile|DBHTMLText
CMSThumbnail()
Default CMS thumbnail
AssetContainer|DBHTMLText
StripThumbnail()
Generates a thumbnail for use in the gridfield view
AssetContainer|DBHTMLText
PreviewThumbnail()
Get preview for this file
AssetContainer
Thumbnail(int $width, int $height)
Default thumbnail generation for Images
AssetContainer|DBHTMLText
ThumbnailIcon(int $width, int $height)
Thubnail generation for all file types.
Resizes images, but returns an icon <img />
tag if this is not a resizable image
DBHTMLText
IconTag()
Get HTML for img containing the icon for this file
string
ThumbnailURL(int $width, int $height)
Get URL to thumbnail of the given size.
May fallback to default icon
AssetContainer|null
Convert(string $toExtension)
Convert the file to another format if there's a registered converter that can handle it.
string
getIcon()
Return the relative URL of an icon for the file type, based on the appCategory() value.
Images are searched for in "framework/images/app_icons/".
Image_Backend
getImageBackend()
Get Image_Backend instance for this image
$this
setImageBackend(Image_Backend $backend)
No description
int
getWidth()
Get the width of this image.
int
getHeight()
Get the height of this image.
int
getOrientation()
Get the orientation of this image.
bool
isSize(int $width, int $height)
Determine if this image is of the specified size
bool
isWidth(int $width)
Determine if this image is of the specified width
bool
isHeight(int $height)
Determine if this image is of the specified width
DBFile|null
manipulateExtension(string $newExtension, callable $callback)
Wrapper for manipulate() that creates a variant file with a different extension than the original file.
DBFile|null
manipulateImage(string $variant, callable $callback)
Wrapper for manipulate that passes in and stores Image_Backend objects instead of tuples
DBFile|null
manipulate(string $variant, callable $callback)
Generate a new DBFile instance using the given callback if it hasn't been created yet, or return the existing one if it has.
string
variantName(string $format, $arg = null)
Name a variant based on a format with arbitrary parameters
array|null
variantParts($variantName)
Reverses variantName().
The "format" part of a variant name is a method name on the owner of this trait. For legacy reasons, there's no delimiter between this part, and the encoded arguments. This means we have to use a whitelist of "known formats", based on methods available on the Image class as the "main" user of this trait. The one exception to this is the variant for swapping file extensions, which is explicitly allowed. This class is commonly decorated with additional manipulation methods through DataExtension.
protected int
castDimension(mixed $value, string $dimension)
Validate a width or size is valid and casts it to integer
bool
IsLazyLoaded()
Determine whether the image should be lazy loaded
AssetContainer
LazyLoad(mixed $lazyLoad)
Set the lazy loading state for this Image
static
get_shortcodes()
No description
static File|null
find(string $filename)
Find a File object by the given filename.
string
Link()
Just an alias function to keep a consistent API with SiteTree
string
AbsoluteLink()
Just an alias function to keep a consistent API with SiteTree
string
getTreeTitle()
No description
bool
hasRestrictedAccess()
Check if the File has a CanViewType set or inherited at "LoggedInUsers or above"
This is a bit different from a canView() check in that it doesn't check anything against a member. Instead it is a member-less permission check
bool
isTrackedFormUpload()
If the file was uploaded via a form and tracked in the database
string
getStatusTitle()
Get title for current file status
static string
get_app_category(string $ext)
Returns a category based on the file extension.
This can be useful when grouping files by type, showing icons on filelinks, etc. Possible group values are: "audio", "mov", "zip", "image".
static array
get_category_extensions(array|string $categories)
For a category or list of categories, get the list of file extensions
string
appCategory()
Returns a category based on the file extension.
onAfterUpload()
Should be called after the file was uploaded
static string
getNormalisedFileName(string $name)
Generate a readable title, dashes and underscores replaced by whitespace, and any file extensions removed.
onAfterRevertToLive()
No description
protected
updateDependantObjects()
Update objects linking to this file
bool
updateFilesystem()
This will check if the parent record and/or name do not match the name on the underlying DBFile record, and if so, copy this file to the new location, and update the record to point to this new file.
This method will update the File {\SilverStripe\Assets\Storage\DBFile} field value on success, so it must be called before writing to the database
true|null
collateDescendants(string $condition, array $collator)
Collate selected descendants of this page.
$condition will be evaluated on each descendant, and if it is succeeds, that item will be added to the $collator array.
protected AssetNameGenerator
getNameGenerator(string $filename)
Get an asset renamer for the given filename.
string
getSourceURL(bool $grant = false)
Get URL, but without resampling.
string
generateFilename()
Get expected value of Filename tuple value. Will be used to trigger a file move on draft stage.
string
renameFile(string $newName)
Rename this file.
Note: This method will immediately save to the database to maintain filesystem consistency with the database.
string
copyFile(string $newName)
Copy to new filename.
This will not automatically point to the new file (as renameFile() does)
$this
setFilename(string $filename)
Update the ParentID and Name for the given filename.
On save, the underlying DBFile record will move the underlying file to this location. Thus it will not update the underlying Filename value until this is done.
string
getExtension()
Returns the file extension
static string
get_file_extension(string $filename)
Gets the extension of a filepath or filename, by stripping away everything before the last "dot".
Caution: Only returns the last extension in "double-barrelled" extensions (e.g. "gz" for "tar.gz").
Examples:
- "myfile" returns ""
- "myfile.txt" returns "txt"
- "myfile.tar.gz" returns "gz"
static string
get_icon_for_extension(string $extension)
Given an extension, determine the icon that should be used
string
getFileType()
Return the type of file for the given extension on the current file name.
static string
get_file_type(string $filename)
Get descriptive type of file based on filename
string|false
getSize()
Returns the size of the file type in an appropriate format.
static string
format_size(int $size)
Formats a file size (eg: (int)42 becomes string '42 bytes')
static string
get_class_for_file_extension($ext)
Maps a File subclass to a specific extension.
By default, files with common image extensions will be created as Image} instead of {@link File when using Folder::constructChild}, {@link Folder::addUploadToFolder), and the Upload} class (either directly or through {@link FileField). For manually instanciated files please use this mapping getter.
Caution: Changes to mapping doesn't apply to existing file records in the database. Also doesn't hook into Object::getCustomClass().
static
set_class_for_file_extension($exts, $class)
See get_class_for_file_extension().
array
setFromLocalFile(string $path, string $filename = null, string $hash = null, string $variant = null, array $config = [])
Assign a local file to the backend.
array
setFromStream(resource $stream, string $filename, string $hash = null, string $variant = null, array $config = [])
Assign a stream to the backend
array
setFromString(string $data, string $filename, string $hash = null, string $variant = null, array $config = [])
Assign a set of data to the backend
string
forTemplate()
Return a html5 tag of the appropriate for this file (normally img or a)
string
getTag()
Return a html5 tag of the appropriate for this file (normally img or a)
DataObject>
BackLinkTracking()
Get the back-link tracking objects that link to this file via HTML fields
int
BackLinkTrackingCount()
Count of backlinks Note: Doesn't filter broken records
static string
join_paths($part = null)
Joins one or more segments together to build a Filename identifier.
Note that the result will not have a leading slash, and should not be used with local file paths.
bool
deleteFile()
Delete a file (and all variants).
string
getVisibility()
Determine visibility of the given file
publishFile()
Publicly expose the file (and all variants) identified by the given filename and hash {AssetStore::publish}
protectFile()
Protect a file (and all variants) from public access, identified by the given filename and hash.
grantFile()
Ensures that access to the specified protected file is granted for the current user.
If this file is currently in protected mode, the asset store will ensure the returned asset for the duration of the current session / user. This will have no effect if the file is in published mode. This will not grant access to users other than the owner of the current session. Does not require a member to be logged in.
revokeFile()
Revoke access to the given file for the current user.
Note: This will have no effect if the given file is public
bool
canViewFile()
Check if the current user can view the given file.
string
CMSEditLink()
No description
string
PreviewLink(string $action = null)
Determine the preview link, if available, for this object.
If no preview is available for this record, it may return null.
PermissionChecker
getPermissionChecker()
No description
providePermissions()
Return a map of permission codes to add to the dropdown shown in the Security section of the CMS.
array( 'VIEW_SITE' => 'View the site', );
static array
getAllowedExtensions()
Get the list of globally allowed file extensions for file uploads.
Specific extensions can be disabled with configuration, for example:
SilverStripe\Assets\File:
allowed_extensions:
dmg: false
docx: false
protected string
filterFilename(string $name)
Pass name through standard FileNameFilter
protected FileNameFilter
getFilter()
No description
void
HasManyList() $FileLink> BackLinks()
No description
Member
Owner()
No description
File
Parent()
No description