Aller au contenu principal
Version: Next

Entity

An entity is an instance of a Dataclass, like a record of the table matching the dataclass in its associated datastore. Elle contient les mêmes attributs que la dataclass ainsi que les valeurs des données et des propriétés et fonctions spécifiques.

Sommaire

.attributeName : any    stocke la valeur de l'attribut pour l'entité
.clone() : 4D.Entity    creates in memory a new entity referencing the same record as the original entity
.diff( entityToCompare : 4D.Entity { ; attributesToCompare : Collection } ) : Collection    compares the contents of two entities and returns their differences
.drop( {mode : Integer} ) : Object    deletes the data contained in the entity from the datastore
.first(): 4D.Entity    returns a reference to the entity in first position of the entity selection which the entity belongs to
.fromObject( filler : Object )    fills an entity with the filler content
.getDataClass() : 4D.DataClass    returns the dataclass of the entity
.getKey( { mode : Integer } ) : Text
.getKey( { mode : Integer } ) : Integer
    returns the primary key value of the entity
.getRemoteContextAttributes() : Text    returns information about the optimization context used by the entity
.getSelection(): 4D.EntitySelection    returns the entity selection which the entity belongs to
.getStamp() : Integer     returns the current value of the stamp of the entity
.indexOf( { entitySelection : 4D.EntitySelection } ) : Integer    returns the position of the entity in an entity selection
.isNew() : Boolean     returns True if the entity to which it is applied has just been created and has not yet been saved in the datastore
.last() : 4D.Entity    returns a reference to the entity in last position of the entity selection which the entity belongs to
.lock( { mode : Integer } ) : Object    puts a pessimistic lock on the record referenced by the entity
.next() : 4D.Entity    returns a reference to the next entity in the entity selection which the entity belongs to
.previous() : 4D.Entity     returns a reference to the previous entity in the entity selection which the entity belongs to
.reload() : Object    reloads the content of the entity in memory
.save( { mode : Integer } ) : Object    saves the changes made to the entity
.toObject() : Object
.toObject( filterString : Text { ; options : Integer} ) : Object
.toObject( filterCol : Collection { ; options : Integer } ) : Object
    returns an object which has been built from the entity
.touched() : Boolean    tests whether or not an entity attribute has been modified since the entity was loaded into memory or saved
.touchedAttributes() : Collection    returns the names of the attributes that have been modified since the entity was loaded into memory
.unlock() : Object    removes the pessimistic lock on the record matching the entity

.attributeName

Historique
ReleaseModifications
17Ajout

.attributeName : any

Description

Tout attribut de dataclass est disponible en tant que propriété des entités de la dataclass, et qui stocke la valeur de l'attribut pour l'entité.

Les attributs de dataclass peuvent également être obtenus en utilisant la syntaxe alternative avec [ ].

The attribute value type depends on the attribute kind (relation or storage):

  • If attributeName kind is storage: .attributeName returns a value of the same type as attributeName.
  • If attributeName kind is relatedEntity: .attributeName returns the related entity. Les valeurs de l'entité liée sont directement disponibles par le biais des propriétés en cascade, par exemple "myEntity.employer.employees[0].lastname".
  • If attributeName kind is relatedEntities: .attributeName returns a new entity selection of related entities. Les doublons sont supprimés (une entity selection non ordonnée est retournée).

Exemple

 var $myEntity : cs.EmployeeEntity
$myEntity:=ds.Employee.new() //Créer une nouvelle entity
$myEntity.name:="Dupont" //assigner 'Dupont' à l'attribut 'name'
$myEntity.firstname:="John" //assigner 'John' à l'attribut 'firstname'
$myEntity.save() //sauvegarder l'entity

.clone()

Historique
ReleaseModifications
17Ajout

.clone() : 4D.Entity

ParamètresTypeDescription
Résultat4D.Entity<-Nouvelle entité référençant l'enregistrement

Description

The .clone() function creates in memory a new entity referencing the same record as the original entity. Cette fonction vous permet de mettre à jour des entités séparément.

Keep in mind that any modifications done to entities will be saved in the referenced record only when the .save( ) function is executed.

Cette fonction ne peut être utilisée qu'avec des entités déjà enregistrées dans la base de données. It cannot be called on a newly created entity (for which .isNew() returns True).

Exemple

 var $emp; $empCloned : cs.EmployeeEntity
$emp:=ds.Employee.get(672)
$empCloned:=$emp.clone()

$emp.lastName:="Smith" //Updates done on $emp are not done on $empCloned

.diff()

Historique
ReleaseModifications
17Ajout

.diff( entityToCompare : 4D.Entity { ; attributesToCompare : Collection } ) : Collection

ParamètresTypeDescription
entityToCompare4D.Entity->Entité à comparer à l'entité d'origine
attributesToCompareCollection->Noms des attributs à comparer
RésultatCollection<-Différences entre les entités

Description

The .diff() function compares the contents of two entities and returns their differences.

In entityToCompare, pass the entity to be compared to the original entity.

In attributesToCompare, you can designate specific attributes to compare. Si le paramètre est passé, la comparaison est effectuée uniquement sur les attributs spécifiés. S'il est omis, toutes les différences entre les entités sont retournées.

Les différences sont retournées sous forme de collection d'objets dont les propriétés sont :

Nom de propriétéTypeDescription
attributeNameStringNom de l'attribut
valueDépend du type d'attributValeur de l'attribut dans l'entité d'origine
otherValueDépend du type d'attributValue of the attribute in entityToCompare

Seuls les attributs dont les valeurs diffèrent sont inclus dans la collection. If no differences are found, .diff() returns an empty collection.

The function applies for properties whose kind is storage or relatedEntity. In case a related entity has been updated (meaning the foreign key), the name of the related entity and its primary key name are returned as attributeName properties (value and otherValue are empty for the related entity name).

If one of the compared entities is Null, an error is raised.

Exemple 1

 var $diff1; $diff2 : Collection
employee:=ds.Employee.query("ID=1001").first()
$clone:=employee.clone()
employee.firstName:="MARIE"
employee.lastName:="SOPHIE"
employee.salary:=500
$diff1:=$clone.diff(employee) // Toutes les différences sont retournées
$diff2:=$clone.diff(employee;New collection("firstName";"lastName"))
// Seules les différences sur firstName et lastName sont retournées

$diff1:

[
{
"attributeName": "firstName",
"value": "Natasha",
"otherValue": "MARIE"
},
{
"attributeName": "lastName",
"value": "Locke",
"otherValue": "SOPHIE"
},
{
"attributeName": "salary",
"value": 66600,
"otherValue": 500
}
]
$diff2:

[
{
"attributeName": "firstName",
"value": "Natasha",
"otherValue": "MARIE"
},
{
"attributeName": "lastName",
"value": "Locke",
"otherValue": "SOPHIE"
}
]

Exemple 2

 var vCompareResult1; vCompareResult2; vCompareResult3; $attributesToInspect : Collection
vCompareResult1:=New collection
vCompareResult2:=New collection
vCompareResult3:=New collection
$attributesToInspect:=New collection

$e1:=ds.Employee.get(636)
$e2:=ds.Employee.get(636)

$e1.firstName:=$e1.firstName+" update"
$e1.lastName:=$e1.lastName+" update"

$c:=ds.Company.get(117)
$e1.employer:=$c
$e2.salary:=100

$attributesToInspect.push("firstName")
$attributesToInspect.push("lastName")

vCompareResult1:=$e1.diff($e2)
vCompareResult2:=$e1.diff($e2;$attributesToInspect)
vCompareResult3:=$e1.diff($e2;$e1.touchedAttributes())

vCompareResult1 (toutes les différences sont retournées) :

[
{
"attributeName": "firstName",
"value": "Karla update",
"otherValue": "Karla"
},
{
"attributeName": "lastName",
"value": "Marrero update",
"otherValue": "Marrero"
},
{
"attributeName": "salary",
"value": 33500,
"otherValue": 100
},
{
"attributeName": "employerID",
"value": 117,
"otherValue": 118
},
{
"attributeName": "employer",
"value": "[object Entity]",// Entity 117 de Company
"otherValue": "[object Entity]"// Entity 118 de Company
}
]

vCompareResult2 (seules les différences sur $attributesToInspect sont retournées)

[
{
"attributeName": "firstName",
"value": "Karla update",
"otherValue": "Karla"
},
{
"attributeName": "lastName",
"value": "Marrero update",
"otherValue": "Marrero"
}
]

vCompareResult3 (seules les différences sur les attributs touchés de $e1 sont retournées)

[
{
"attributeName": "firstName",
"value": "Karla update",
"otherValue": "Karla"
},
{
"attributeName": "lastName",
"value": "Marrero update",
"otherValue": "Marrero"
},
{
"attributeName": "employerID",
"value": 117,
"otherValue": 118
},
{
"attributeName": "employer",
"value": "[object Entity]",// Entity 117 de Company
"otherValue": "[object Entity]"// Entity 118 de Company

}
]

.drop()

Historique
ReleaseModifications
17Ajout

.drop( {mode : Integer} ) : Object

ParamètresTypeDescription
modeInteger->dk force drop if stamp changed: Forces the drop even if the stamp has changed
RésultatObject<-Résultat de l'opération de suppression

Description

The .drop() function deletes the data contained in the entity from the datastore, from the table related to its Dataclass. A noter que l'entité reste en mémoire.

In a multi-user or multi-process application, the .drop() function is executed under an "optimistic lock" mechanism, wherein an internal locking stamp is automatically incremented each time the record is saved.

By default, if the mode parameter is omitted, the function will return an error (see below) if the same entity was modified (i.e. the stamp has changed) by another process or user in the meantime.

Otherwise, you can pass the dk force drop if stamp changed option in the mode parameter: in this case, the entity is dropped even if the stamp has changed (and the primary key is still the same).

Result

The object returned by .drop( ) contains the following properties:

PropriétéTypeDescription
successbooleanvrai si l'action de suppression a été effectuée avec succès, sinon Faux.
Available only in case of error:
status(*)numberCode d'erreur, voir ci-dessous
statusText(*)textDescription de l'erreur, voir ci-dessous
Available only in case of pessimistic lock error:
LockKindTexttext"Locked by record"
lockInfoobjectInformation sur l'origine du verrouillage
task_idnumberId du process
user_nametextNom d'utilisateur de la session sur la machine
user4d_aliastextUser alias if defined by SET USER ALIAS, otherwise user name in the 4D directory
host_nametextNom de la machine
task_nametextNom du process
client_versiontext
Available only in case of serious error (serious error can be trying to duplicate a primary key, disk full...):
errorscollection of objects
messagetextMessage d'erreur
component signaturetextsignature du composant interne (e.g. "dmbg" pour le composant de base de données)
errCodenumberCode d'erreur

(*) The following values can be returned in the status and statusText properties of Result object in case of error:

ConstanteValeurCommentaire
dk status entity does not exist anymore5L'entité n'existe plus dans les données. This error can occur in the following cases:
  • the entity has been dropped (the stamp has changed and the memory space is now free)
  • the entity has been dropped and replaced by another one with another primary key (the stamp has changed and a new entity now uses the memory space). Avec drop( ), cette erreur peut être retournée lorsque l'option dk force drop if stamp changed est utilisée. When using entity.lock( ), this error can be returned when dk reload if stamp changed option is used
  • Associated statusText: "Entity does not exist anymore"
    dk status locked3The entity is locked by a pessimistic lock.
    Associated statusText: "Already locked"
    dk status serious error4A serious error is a low-level database error (e.g. duplicated key), a hardware error, etc.
    Associated statusText: "Other error"
    dk status stamp has changed2The internal stamp value of the entity does not match the one of the entity stored in the data (optimistic lock).
  • with .save( ): error only if the dk auto merge option is not used
  • with .drop( ): error only if the dk force drop if stamp changed option is not used
  • with .lock( ): error only if the dk reload if stamp changed option is not used
  • Associated statusText: "Stamp has changed"
  • dk status wrong permission1Les privilèges courants ne permettent pas de supprimer l'entité. Associated statusText: "Permission Error"

    Exemple 1

    Example without dk force drop if stamp changed option:

     var $employees : cs.EmployeeSelection
    var $employee : cs.EmployeeEntity
    var $status : Object
    $employees:=ds.Employee.query("lastName=:1";"Smith")
    $employee:=$employees.first()
    $status:=$employee.drop()
    Case of
    :($status.success)
    ALERT("You have dropped "+$employee.firstName+" "+$employee.lastName) //The dropped entity remains in memory
    :($status.status=dk status stamp has changed)
    ALERT($status.statusText)
    End case

    Exemple 2

    Example with dk force drop if stamp changed option:

     var $employees : cs.EmployeeSelection
    var $employee : cs.EmployeeEntity
    var $status : Object
    $employees:=ds.Employee.query("lastName=:1";"Smith")
    $employee:=$employees.first()
    $status:=$employee.drop(dk force drop if stamp changed)
    Case of
    :($status.success)
    ALERT("You have dropped "+$employee.firstName+" "+$employee.lastName) //The dropped entity remains in memory
    :($status.status=dk status entity does not exist anymore)
    ALERT($status.statusText)
    End case

    .first()

    Historique
    ReleaseModifications
    17Ajout

    .first(): 4D.Entity

    ParamètresTypeDescription
    Résultat4D.Entity<-Référence à la première entité de l'entity selection (Null si non trouvée)

    Description

    The .first() function returns a reference to the entity in first position of the entity selection which the entity belongs to.

    If the entity does not belong to any existing entity selection (i.e. .getSelection( ) returns Null), the function returns a Null value.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee; $firstEmployee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName = :1";"H@") //This entity selection contains 3 entities
    $employee:=$employees[2]
    $firstEmployee:=$employee.first() //$firstEmployee is the first entity of the $employees entity selection

    .fromObject()

    Historique
    ReleaseModifications
    17Ajout

    .fromObject( filler : Object )

    ParamètresTypeDescription
    fillerObject->Objet avec lequel remplir l'entité

    Description

    The .fromObject() function fills an entity with the filler content.

    Cette fonction modifie l'entity d'origine.

    La correspondance entre l'objet et l'entité est établie à partir des noms de propriétés/d'attributs :

    • Si une propriété de l'objet n'existe pas dans la dataclass, elle est ignorée.
    • Les types de données doivent être équivalents. If there is a type mismatch between the object and dataclass, 4D tries to convert the data whenever possible (see Converting data types), otherwise the attribute is left untouched.
    • La clé primaire peut être donnée telle quelle ou avec une propriété "__KEY" (remplie avec la valeur de la clé primaire). If it does not already exist in the dataclass, the entity is created with the given value when .save() is called. Si la clé primaire n'est pas fournie, l'entité est créée et la valeur de la clé primaire est affectée en fonction des règles de la base de données. L'auto-incrémentation n'est calculée que si la clé primaire est nulle.

    filler can handle a related entity under the following conditions:

    • filler contains the foreign key itself, or
    • filler contains a property object with the same name as the related entity, containing a single property named "__KEY".
    • si l'entité relative n'existe pas, elle est ignorée.

    Exemple

    Avec l'objet $o suivant :

    {
    "firstName": "Mary",
    "lastName": "Smith",
    "salary": 36500,
    "birthDate": "1958-10-27T00:00:00.000Z",
    "woman": true,
    "managerID": 411,// relatedEntity fournie avec clé primaire
    "employerID": 20 // relatedEntity fournie avec clé primaire
    }

    Le code suivant créera une entité avec les entités relatives manager et employer.

     var $o : Object
    var $entity : cs.EmpEntity
    $entity:=ds.Emp.new()
    $entity.fromObject($o)
    $entity.save()

    Vous pouvez également utiliser une entité relative fournie sous forme d'objet :


    {
    "firstName": "Marie",
    "lastName": "Lechat",
    "salary": 68400,
    "birthDate": "1971-09-03T00:00:00.000Z",
    "woman": false,
    "employer": {// relatedEntity given as an object
    "__KEY": "21"
    },
    "manager": {// relatedEntity given as an object
    "__KEY": "411"
    }
    }

    .getDataClass()

    Historique
    ReleaseModifications
    17 R5Ajout

    .getDataClass() : 4D.DataClass

    ParamètresTypeDescription
    Résultat4D.DataClass<-Dataclass à laquelle appartient l'entité

    Description

    The .getDataClass() function returns the dataclass of the entity. Cette fonction est utile pour l'écriture du code générique.

    Exemple

    Le code générique suivant duplique toute entité :

      //duplicate_entity method
    //duplicate_entity($entity)

    #DECLARE($entity : 4D.Entity)
    var $entityNew : 4D.Entity
    var $status : Object

    $entityNew:=$entity.getDataClass().new() //create a new entity in the parent dataclass
    $entityNew.fromObject($entity.toObject()) //get all attributes
    $entityNew[$entity.getDataClass().getInfo().primaryKey]:=Null //reset the primary key
    $status:=$entityNew.save() //save the duplicated entity

    .getKey()

    Historique
    ReleaseModifications
    17Ajout

    .getKey( { mode : Integer } ) : Text
    .getKey( { mode : Integer } ) : Integer

    ParamètresTypeDescription
    modeInteger->dk key as string: primary key is returned as a string, no matter the primary key type
    RésultatText<-Valeur de la clé primaire texte de l'entité
    RésultatInteger<-Valeur de la clé primaire numérique de l'entité

    Description

    The .getKey() function returns the primary key value of the entity.

    Les clés primaires peuvent être des nombres (integer) ou des textes. You can "force" the returned primary key value to be a string, no matter the actual primary key type, by passing the dk key as string option in the mode parameter.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName=:1";"Smith")
    $employee:=$employees[0]
    ALERT("The primary key is "+$employee.getKey(dk key as string))

    .getRemoteContextAttributes()

    Historique
    ReleaseModifications
    19R5Ajout

    .getRemoteContextAttributes() : Text

    ParamètresTypeDescription
    resultText<-Attirbuts de contexte associés à l'entity, séparés par une virgule

    Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Dans la plupart des cas, vous n'aurez pas besoin de l'utiliser.

    Description

    The .getRemoteContextAttributes() function returns information about the optimization context used by the entity .

    If there is no optimization context for the entity, the function returns an empty Text.

    Exemple

    var $ds : 4D.DataStoreImplementation
    var $address : cs.AddressEntity
    var $p : cs.PersonsEntity
    var $contextA : Object
    var $info : Text
    var $text : Text

    $ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")

    $contextA:=New object("context"; "contextA")

    $address:=$ds.Address.get(1; $contextA)
    $text:=""
    For each ($p; $address.persons)
    $text:=$p.firstname+" "+$p.lastname
    End for each

    $info:=$address.getRemoteContextAttributes()

    //$info = "persons,persons.lastname,persons.firstname"

    Voir également

    EntitySelection.getRemoteContextAttributes()
    .clearAllRemoteContexts()
    .getRemoteContextInfo()
    .getAllRemoteContexts()
    .setRemoteContextInfo()

    .getSelection()

    Historique
    ReleaseModifications
    17Ajout

    .getSelection(): 4D.EntitySelection

    ParamètresTypeDescription
    Résultat4D.EntitySelection<-Entity selection à laquelle appartient l'entité (Null si non trouvée)

    Description

    The .getSelection() function returns the entity selection which the entity belongs to.

    Si l'entité n'appartient pas à une entity selection, la fonction renvoie Null.

    Exemple

     var $emp : cs.EmployeeEntity
    var $employees; $employees2 : cs.EmployeeSelection
    $emp:=ds.Employee.get(672) // This entity does not belong to any entity selection
    $employees:=$emp.getSelection() // $employees is Null

    $employees2:=ds.Employee.query("lastName=:1";"Smith") //This entity selection contains 6 entities
    $emp:=$employees2[0] // This entity belongs to an entity selection

    ALERT("The entity selection contains "+String($emp.getSelection().length)+" entities")

    .getStamp()

    Historique
    ReleaseModifications
    17Ajout

    .getStamp() : Integer

    ParamètresTypeDescription
    RésultatInteger<-Valeur du "stamp" de l'entité (0 si l'entité vient d'être créée)

    Description

    The .getStamp() function returns the current value of the stamp of the entity.

    Le stamp (marqueur interne) d'une entité est automatiquement incrémenté par 4D à chaque fois qu'une entité est enregistrée sur disque. It manages concurrent user access and modifications to the same entities (see Entity locking).

    Pour une nouvelle entité (jamais enregistrée), la fonction retourne 0. To know if an entity has just been created, it is recommended to use .isNew().

    Exemple

     var $entity : cs.EmployeeEntity
    var $stamp : Integer

    $entity:=ds.Employee.new()
    $entity.lastname:="Smith"
    $entity.save()
    $stamp:=$entity.getStamp() //$stamp=1

    $entity.lastname:="Wesson"
    $entity.save()
    $stamp:=$entity.getStamp() //$stamp=2

    .indexOf()

    Historique
    ReleaseModifications
    17Ajout

    .indexOf( { entitySelection : 4D.EntitySelection } ) : Integer

    ParamètresTypeDescription
    entitySelection4D.EntitySelection->Entity selection dans laquelle obtenir la position de l'entité
    RésultatInteger<-Position de l'entité dans l'entity selection

    Description

    The .indexOf() function returns the position of the entity in an entity selection.

    By default if the entitySelection parameter is omitted, the function returns the entity's position within its own entity selection. Otherwise, it returns the position of the entity within the specified entitySelection.

    La valeur résultante est comprise entre 0 et la longueur de l'entity selection -1.

    • If the entity does not have an entity selection or does not belong to entitySelection, the function returns -1.
    • If entitySelection is Null or does not belong to the same dataclass as the entity, an error is raised.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName = :1";"H@") //This entity selection contains 3 entities
    $employee:=$employees[1] //This entity belongs to an entity selection
    ALERT("The index of the entity in its own entity selection is "+String($employee.indexOf())) //1

    $employee:=ds.Employee.get(725) //This entity does not belong to an entity selection
    ALERT("The index of the entity is "+String($employee.indexOf())) // -1

    .isNew()

    Historique
    ReleaseModifications
    17Ajout

    .isNew() : Boolean

    ParamètresTypeDescription
    RésultatBoolean<-Vrai si l'entité vient juste d'être créée et n'a pas encore été enregistrée. Sinon, Faux.

    Description

    The .isNew() function returns True if the entity to which it is applied has just been created and has not yet been saved in the datastore. Sinon, elle renvoie Faux.

    Exemple

     var $emp : cs.EmployeeEntity

    $emp:=ds.Employee.new()

    If($emp.isNew())
    ALERT("This is a new entity")
    End if

    .last()

    Historique
    ReleaseModifications
    17Ajout

    .last() : 4D.Entity

    ParamètresTypeDescription
    Résultat4D.Entity<-Référence à la dernière entité de l'entity selection (Null si non trouvée)

    Description

    The .last() function returns a reference to the entity in last position of the entity selection which the entity belongs to.

    If the entity does not belong to any existing entity selection (i.e. .getSelection( ) returns Null), the function returns a Null value.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee; $lastEmployee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName = :1";"H@") //This entity selection contains 3 entities
    $employee:=$employees[0]
    $lastEmployee:=$employee.last() //$lastEmployee is the last entity of the $employees entity selection

    .lock()

    Historique
    ReleaseModifications
    17Ajout

    .lock( { mode : Integer } ) : Object

    ParamètresTypeDescription
    modeInteger->dk reload if stamp changed: Reload before locking if stamp changed
    RésultatObject<-Résultat de l'opération lock

    Description

    The .lock() function puts a pessimistic lock on the record referenced by the entity. The lock is set for a record and all the references of the entity in the current process.

    Other processes will see this record as locked (the result.success property will contain False if they try to lock the same entity using this function). Seules les fonctions exécutées dans la session à l'origine du verrouillage auront la possibilité de modifier et de sauvegarder les attributs de l'entité. L'entité peut être chargée en lecture seulement dans les autres sessions, mais elles ne pourront ni saisir ni sauvegarder des valeurs.

    A record locked by .lock() is unlocked:

    • when the unlock() function is called on a matching entity in the same process
    • automatiquement, lorsqu'elle n'est plus référencée par aucune entité en mémoire. Par exemple, si le verrou n'est posé que sur une référence locale d'une entité, celle-ci est déverrouillée à la fin de la fonction. Tant qu'il existe des références à l'entité en mémoire, l'enregistrement reste verrouillé.

    An entity can also be locked by a REST session, in which case it can only be unlocked by the session.

    By default, if the mode parameter is omitted, the function will return an error (see below) if the same entity was modified (i.e. the stamp has changed) by another process or user in the meantime.

    Otherwise, you can pass the dk reload if stamp changed option in the mode parameter: in this case, no error is returned and the entity is reloaded when the stamp has changed (if the entity still exists and the primary key is still the same).

    Result

    The object returned by .lock( ) contains the following properties:

    PropriétéTypeDescription
    successbooleanvrai si l'action de verrouillage a été effectuée avec succès (ou si l'entité est déjà verrouillée dans le process courant), sinon faux.
    Available only if dk reload if stamp changed option is used:
    wasReloadedbooleanvrai si l'entité a été correctement rechargée, sinon faux.
    Available only in case of error:
    status(*)numberCode d'erreur, voir ci-dessous
    statusText(*)textDescription de l'erreur, voir ci-dessous
    Available only in case of pessimistic lock error:
    lockKindTexttext"Locked by record" si verrouillage par un process 4D, "Locked by session" si verrouillage par une session REST
    lockInfoobjectInformation sur l'origine du verrouillage. Les propriétés retournées dépendent de l'origine du verrouillage (process 4D ou session REST).
    Available only for a 4D process lock:
    task_idnumberID du process
    user_nametextNom d'utilisateur de la session sur la machine
    user4d_aliastextNom ou alias de l'utilisateur 4D
    user4d_idnumberIdentifiant utilisateur dans le répertoire de la base 4D
    host_nametextNom de la machine
    task_nametextNom du process
    client_versiontextVersion du client
    Available only for a REST session lock:
    hosttext|URL that locked the entity (e.g. "www.myserver.com")\|
    IPAddrtextAdresse IP d'origine du verrouillage (ex. 127.0.0.1")
    userAgenttextuserAgent de l'origine du verouillage (ex : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")
    Available only in case of serious error (primary key already exists, disk full...):
    errorscollection of objects
    messagetextMessage d'erreur
    component signaturetextsignature du composant interne (e.g. "dmbg" pour le composant de base de données)
    errCodenumberCode d'erreur

    (*) The following values can be returned in the status and statusText properties of the Result object in case of error:

    ConstanteValeurCommentaire
    dk status entity does not exist anymore5L'entité n'existe plus dans les données. This error can occur in the following cases:
  • the entity has been dropped (the stamp has changed and the memory space is now free)
  • the entity has been dropped and replaced by another one with another primary key (the stamp has changed and a new entity now uses the memory space). Avec .drop( ), cette erreur peut être retournée lorsque l'option dk force drop if stamp changed est utilisée. When using .lock( ), this error can be returned when dk reload if stamp changed option is used

  • Associated statusText: "Entity does not exist anymore"
    dk status locked3The entity is locked by a pessimistic lock.Associated statusText: "Already locked"
    dk status serious error4A serious error is a low-level database error (e.g. duplicated key), a hardware error, etc.Associated statusText: "Other error"
    dk status stamp has changed2The internal stamp value of the entity does not match the one of the entity stored in the data (optimistic lock).
  • with .save( ): error only if the dk auto merge option is not used
  • with .drop( ): error only if the dk force drop if stamp changed option is not used
  • with .lock( ): error only if the dk reload if stamp changed option is not used

  • Associated statusText: "Stamp has changed"

    Exemple 1

    Exemple avec erreur :

     var $employee : cs.EmployeeEntity
    var $status : Object
    $employee:=ds.Employee.get(716)
    $status:=$employee.lock()
    Case of
    :($status.success)
    ALERT("You have locked "+$employee.firstName+" "+$employee.lastName)
    :($status.status=dk status stamp has changed)
    ALERT($status.statusText)
    End case

    Exemple 2

    Example with dk reload if stamp changed option:

     var $employee : cs.EmployeeEntity
    var $status : Object
    $employee:=ds.Employee.get(717)
    $status:=$employee.lock(dk reload if stamp changed)
    Case of
    :($status.success)
    ALERT("You have locked "+$employee.firstName+" "+$employee.lastName)
    :($status.status=dk status entity does not exist anymore)
    ALERT($status.statusText)
    End case

    .next()

    Historique
    ReleaseModifications
    17Ajout

    .next() : 4D.Entity

    ParamètresTypeDescription
    Résultat4D.Entity<-Référence à l'entité suivante dans l'entity selection (Null si non trouvée)

    Description

    The .next() function returns a reference to the next entity in the entity selection which the entity belongs to.

    If the entity does not belong to any existing entity selection (i.e. .getSelection() returns Null), the function returns a Null value.

    If the entity does not belong to any existing entity selection (i.e. .getSelection( ) returns Null), the function returns a Null value.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee; $nextEmployee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName = :1";"H@") //This entity selection contains 3 entities
    $employee:=$employees[0]
    $nextEmployee:=$employee.next() //$nextEmployee is the second entity of the $employees entity selection

    .previous()

    Historique
    ReleaseModifications
    17Ajout

    .previous() : 4D.Entity

    ParamètresTypeDescription
    Résultat4D.Entity<-Référence à l'entité précédente dans l'entity selection (Null si non trouvée)

    Description

    The .previous() function returns a reference to the previous entity in the entity selection which the entity belongs to.

    If the entity does not belong to any existing entity selection (i.e. .getSelection() returns Null), the function returns a Null value.

    If the entity does not belong to any existing entity selection (i.e. .getSelection( ) returns Null), the function returns a Null value.

    Exemple

     var $employees : cs.EmployeeSelection
    var $employee; $previousEmployee : cs.EmployeeEntity
    $employees:=ds.Employee.query("lastName = :1";"H@") //This entity selection contains 3 entities
    $employee:=$employees[1]
    $previousEmployee:=$employee.previous() //$previousEmployee is the first entity of the $employees entity selection

    .reload()

    Historique
    ReleaseModifications
    17Ajout

    .reload() : Object

    ParamètresTypeDescription
    RésultatObject<-Objet statut

    Description

    The .reload() function reloads the content of the entity in memory, according to information stored in the table related to the dataclass in the datastore. Le rechargement est effectué uniquement si l'entité existe toujours avec la même clé primaire.

    Result

    The object returned by .reload( ) contains the following properties:

    PropriétéTypeDescription
    successbooleanTrue if the reload action is successful, False otherwise.Available only in case of error:
    status(*)numberCode d'erreur, voir ci-dessous
    statusText(*)textDescription de l'erreur, voir ci-dessous

    (*) The following values can be returned in the status and statusText properties of Result object in case of error:

    ConstanteValeurCommentaire
    dk status entity does not exist anymore5L'entité n'existe plus dans les données. This error can occur in the following cases:
  • the entity has been dropped (the stamp has changed and the memory space is now free)
  • the entity has been dropped and replaced by another one with another primary key (the stamp has changed and a new entity now uses the memory space). Avec .drop( ), cette erreur peut être retournée lorsque l'option dk force drop if stamp changed est utilisée. When using .lock( ), this error can be returned when dk reload if stamp changed option is used

  • Associated statusText: "Entity does not exist anymore"
    dk status serious error4A serious error is a low-level database error (e.g. duplicated key), a hardware error, etc.
    Associated statusText: "Other error"

    Exemple

     var $employee : cs.EmployeeEntity
    var $employees : cs.EmployeeSelection
    var $result : Object

    $employees:=ds.Employee.query("lastName=:1";"Hollis")
    $employee:=$employees[0]
    $employee.firstName:="Mary"
    $result:=$employee.reload()
    Case of
    :($result.success)
    ALERT("Reload has been done")
    :($result.status=dk status entity does not exist anymore)
    ALERT("The entity has been dropped")
    End case

    .save()

    Historique
    ReleaseModifications
    17Ajout

    .save( { mode : Integer } ) : Object

    ParamètresTypeDescription
    modeInteger->dk auto merge: Enables the automatic merge mode
    RésultatObject<-Résultat de la sauvegarde

    Description

    The .save() function saves the changes made to the entity in the table related to its dataClass. Vous devez appeler cette fonction après toute création ou modification d'entité si vous souhaitez sauvegarder les changements.

    The save operation is executed only if at least one entity attribute has been "touched" (see the .touched() and .touchedAttributes() functions). Sinon, la fonction ne fait rien (le trigger n'est pas appelé).

    In a multi-user or multi-process application, the .save() function is executed under an "optimistic lock" mechanism, wherein an internal locking stamp is automatically incremented each time the record is saved.

    By default, if the mode parameter is omitted, the method will return an error (see below) whenever the same entity has been modified by another process or user in the meantime, no matter the modified attribute(s).

    Otherwise, you can pass the dk auto merge option in the mode parameter: when the automatic merge mode is enabled, a modification done concurrently by another process/user on the same entity but on a different attribute will not result in an error. Les données effectivement stockées dans l'enregistrement résultent alors de la combinaison (le "merge") des modifications non-concurrentes (si des modifications ont été effectuées sur le même attribut, la sauvegarde échoue et une erreur est retournée, même en mode "automatic merge").

    Le mode de fusion automatique n'est pas disponible pour les attributs de type Image, Objet et Texte lorsqu'ils sont stockés en dehors de l'enregistrement. Concurrent changes in these attributes will result in a dk status stamp has changed error.

    Result

    The object returned by .save() contains the following properties:

    PropriétéTypeDescription
    successbooleanVrai si la sauvegarde a été effectuée avec succès, sinon faux.
    Available only if dk auto merge option is used:
    autoMergedbooleanVrai si un "auto merge" a été effectué, sinon faux.
    Available only in case of error:
    statusnumberError code, see below
    statusTexttextDescription of the error, see below
    Available only in case of pessimistic lock error:
    lockKindTexttext"Locked by record"
    lockInfoobjectInformation sur l'origine du verrouillage
    task_idnumberId du process
    user_nametextNom d'utilisateur de la session sur la machine
    user4d_aliastextUser alias if defined by SET USER ALIAS, otherwise user name in the 4D directory
    host_nametextNom de la machine
    task_nametextNom du process
    client_versiontext
    Available only in case of serious error (serious error - can be trying to duplicate a primary key, disk full...):
    errorscollection of objects
    messagetextMessage d'erreur
    componentSignaturetextSignature du composant interne (e.g. "dmbg" pour le composant de base de données)
    errCodenumberCode d'erreur
    status et statusText

    The following values can be returned in the status and statusText properties of Result object in case of error:

    ConstanteValeurCommentaire
    dk status automerge failed6(Only if the dk auto merge option is used) The automatic merge option failed when saving the entity.Associated statusText: "Auto merge failed"
    dk status entity does not exist anymore5L'entité n'existe plus dans les données. This error can occur in the following cases:
  • the entity has been dropped (the stamp has changed and the memory space is now free)
  • the entity has been dropped and replaced by another one with another primary key (the stamp has changed and a new entity now uses the memory space). Avec .drop( ), cette erreur peut être retournée lorsque l'option dk force drop if stamp changed est utilisée. When using .lock( ), this error can be returned when dk reload if stamp changed option is used

  • Associated statusText: "Entity doesnot exist anymore"
    dk status locked3The entity is locked by a pessimistic lock.Associated statusText: "Already locked"
    dk status serious error4A serious error is a low-level database error (e.g. duplicated key), a hardware error, etc.Associated statusText: "Other error"
    dk status stamp has changed2The internal stamp value of the entity does not match the one of the entity stored in the data (optimistic lock).
  • with .save( ): error only if the dk auto merge option is not used
  • with .drop( ): error only if the dk force drop if stamp changed option is not used
  • with .lock( ): error only if the dk reload if stamp changed option is not used

  • Associated statusText: "Stamp has changed"
    dk status wrong permission1Les privilèges courants ne permettent pas de supprimer l'entité. Associated statusText: "Permission Error"

    Exemple 1

    Création d'une entité :

     var $status : Object
    var $employee : cs.EmployeeEntity
    $employee:=ds.Employee.new()
    $employee.firstName:="Mary"
    $employee.lastName:="Smith"
    $status:=$employee.save()
    If($status.success)
    ALERT("Employee created")
    End if

    Exemple 2

    Updating an entity without dk auto merge option:

     var $status : Object
    var $employee : cs.EmployeeEntity
    var $employees : cs.EmployeeSelection
    $employees:=ds.Employee.query("lastName=:1";"Smith")
    $employee:=$employees.first()
    $employee.lastName:="Mac Arthur"
    $status:=$employee.save()
    Case of
    :($status.success)
    ALERT("Employee updated")
    :($status.status=dk status stamp has changed)
    ALERT($status.statusText)
    End case

    Exemple 3

    Updating an entity with dk auto merge option:

     var $status : Object

    var $employee : cs.EmployeeEntity
    var $employees : cs.EmployeeSelection

    $employees:=ds.Employee.query("lastName=:1";"Smith")
    $employee:=$employees.first()
    $employee.lastName:="Mac Arthur"
    $status:=$employee.save(dk auto merge)
    Case of
    :($status.success)
    ALERT("Employee updated")
    :($status.status=dk status automerge failed)
    ALERT($status.statusText)
    End case

    .toObject()

    Historique
    ReleaseModifications
    17Ajout

    .toObject() : Object
    .toObject( filterString : Text { ; options : Integer} ) : Object
    .toObject( filterCol : Collection { ; options : Integer } ) : Object

    ParamètresTypeDescription
    filterStringText->Attribut(s) à extraire (chaînes séparées par des virgules)
    filterColCollection->Collection d'attribut(s) à extraire
    optionsInteger->dk with primary key: adds the __KEY property;
    dk with stamp: adds the _STAMP property
    RésultatObject<-Objet généré à partir de l'entité

    Description

    The .toObject() function returns an object which has been built from the entity. Les noms des propriétés de l'objet correspondent aux noms des attributs de l'entité.

    If no filter is specified, or if the filterString parameter contains an empty string or "*", the returned object will contain:

    • tous les attributs storage de l'entité
    • attributes of the relatedEntity kind: you get a property with the same name as the related entity (name of the many-to-one link). L'attribut est extrait sous forme simple.
    • attributes of the relatedEntities kind: attribute is not returned.

    Dans le premier paramètre, indiquez le ou les attribut(s) à extraire. Vous pouvez passer :

    • filterString: a string with property paths separated with commas: "propertyPath1, propertyPath2, ...", or
    • filterCol: a collection of strings: ["propertyPath1","propertyPath2";...]

    If a filter is specified for attributes of the relatedEntity kind:

    • propertyPath = "relatedEntity" -> it is extracted with simple form: an object with property __KEY (primary key).
    • propertyPath = "relatedEntity.*" -> all the properties are extracted
    • propertyPath = "relatedEntity.propertyName1; relatedEntity.propertyName2; ..." -> only those properties are extracted

    If a filter is specified for attributes of the relatedEntities kind:

    • propertyPath = "relatedEntities.*" -> all the properties are extracted
    • propertyPath = "relatedEntities.propertyName1; relatedEntities.propertyName2; ..." -> only those properties are extracted

    In the options parameter, you can pass the dk with primary key and/ordk with stamp selector(s) to add the entity's primary keys and/or stamps in extracted objects.

    Warning

    Si vous utilisez un autre attribut que la clé primaire comme attribut 1 dans une relation, la valeur de cet attribut sera inscrite dans la propriété "__KEY". Keep in mind that it is recommended to use the primary key as One attribute in your relations, especially when you use .toObject() and .fromObject() functions.

    Exemple 1

    La structure suivante sera utilisée pour les exemples de cette section :

    Sans paramètre filtre :

    employeeObject:=employeeSelected.toObject()

    Retourne :

    {
    "ID": 413,
    "firstName": "Greg",
    "lastName": "Wahl",
    "salary": 0,
    "birthDate": "1963-02-01T00:00:00.000Z",
    "woman": false,
    "managerID": 412,
    "employerID": 20,
    "photo": "[object Picture]",
    "extra": null,
    "employer": { // relatedEntity extraite sous forme simple
    "__KEY": 20
    },
    "manager": {
    "__KEY": 412
    }
    }

    Exemple 2

    Extraction de la clé primaire et du stamp :

    employeeObject:=employeeSelected.toObject("";dk with primary key+dk with stamp)

    Retourne :

    {
    "__KEY": 413,
    "__STAMP": 1,
    "ID": 413,
    "firstName": "Greg",
    "lastName": "Wahl",
    "salary": 0,
    "birthDate": "1963-02-01T00:00:00.000Z",
    "woman": false,
    "managerID": 412,
    "employerID": 20,
    "photo": "[object Picture]",
    "extra": null,
    "employer": {
    "__KEY": 20
    },
    "manager": {
    "__KEY": 412
    }
    }

    Exemple 3

    Expanding all the properties of relatedEntities:

    employeeObject:=employeeSelected.toObject("directReports.*")
    {
    "directReports": [
    {
    "ID": 418,
    "firstName": "Lorena",
    "lastName": "Boothe",
    "salary": 44800,
    "birthDate": "1970-10-02T00:00:00.000Z",
    "woman": true,
    "managerID": 413,
    "employerID": 20,
    "photo": "[object Picture]",
    "extra": null,
    "employer": {
    "__KEY": 20
    },
    "manager": {
    "__KEY": 413
    }
    },
    {
    "ID": 419,
    "firstName": "Drew",
    "lastName": "Caudill",
    "salary": 41000,
    "birthDate": "2030-01-12T00:00:00.000Z",
    "woman": false,
    "managerID": 413,
    "employerID": 20,
    "photo": "[object Picture]",
    "extra": null,
    "employer": {
    "__KEY": 20
    },
    "manager": {
    "__KEY": 413
    }
    },
    {
    "ID": 420,
    "firstName": "Nathan",
    "lastName": "Gomes",
    "salary": 46300,
    "birthDate": "2010-05-29T00:00:00.000Z",
    "woman": false,
    "managerID": 413,
    "employerID": 20,
    "photo": "[object Picture]",
    "extra": null,
    "employer": {
    "__KEY": 20
    },
    "manager": {
    "__KEY": 413
    }
    }
    ]
    }

    Exemple 4

    Extracting some properties of relatedEntities:

     employeeObject:=employeeSelected.toObject("firstName, directReports.lastName")

    Retourne :

    {
    "firstName": "Greg",
    "directReports": [
    {
    "lastName": "Boothe"
    },
    {
    "lastName": "Caudill"
    },
    {
    "lastName": "Gomes"
    }
    ]
    }

    Exemple 5

    Extracting a relatedEntity with simple form:

     $coll:=New collection("firstName";"employer")
    employeeObject:=employeeSelected.toObject($coll)

    Retourne :

    {
    "firstName": "Greg",
    "employer": {
    "__KEY": 20
    }
    }

    Exemple 6

    Extracting all the properties of a relatedEntity:

     employeeObject:=employeeSelected.toObject("employer.*")

    Retourne :

    {
    "employer": {
    "ID": 20,
    "name": "India Astral Secretary",
    "creationDate": "1984-08-25T00:00:00.000Z",
    "revenues": 12000000,
    "extra": null
    }
    }

    Exemple 7

    Extracting some properties of a relatedEntity:

     $col:=New collection
    $col.push("employer.name")
    $col.push("employer.revenues")
    employeeObject:=employeeSelected.toObject($col)

    Retourne :

    {
    "employer": {
    "name": "India Astral Secretary",
    "revenues": 12000000
    }
    }

    .touched( )

    Historique
    ReleaseModifications
    17Ajout

    .touched() : Boolean

    ParamètresTypeDescription
    RésultatBoolean<-Vrai si au moins un attribut de l'entité a été modifié et non encore sauvegardé, sinon Faux

    Description

    The .touched() function tests whether or not an entity attribute has been modified since the entity was loaded into memory or saved.

    Si un attribut a été modifié ou calculé, la fonction retourne Vrai, sinon elle retourne Faux. Vous pouvez utiliser cette fonction pour savoir s'il est nécessaire de sauvegarder l'entité.

    This function returns False for a new entity that has just been created (with .new( )). Note however that if you use a function which calculates an attribute of the entity, the .touched() function will then return True. For example, if you call .getKey() to calculate the primary key, .touched() returns True.

    Exemple

    Cet exemple vérifie s'il est nécessaire de sauvegarder l'entité :

     var $emp : cs.EmployeeEntity
    $emp:=ds.Employee.get(672)
    $emp.firstName:=$emp.firstName //Même réassigné avec sa propre valeur, l'attribut est considéré "touched"

    If($emp.touched()) //si au moins l'un des attributs a été modifié
    $emp.save()
    End if // sinon, inutile de sauvegarder l'entité

    .touchedAttributes( )

    Historique
    ReleaseModifications
    17Ajout

    .touchedAttributes() : Collection

    ParamètresTypeDescription
    RésultatCollection<-Noms des attributs touchés ou collection vide

    Description

    The .touchedAttributes() function returns the names of the attributes that have been modified since the entity was loaded into memory.

    This applies for attributes of the kind storage or relatedEntity.

    Dans le cas d'un attribut relationnel ayant été "touché" (i.e., la clé étrangère), le nom de l'entité liée et celui de sa clé primaire sont retournés.

    Si aucun attribut de l'entité n'a été touché, la fonction retourne une collection vide.

    Exemple 1

     var $touchedAttributes : Collection
    var $emp : cs.EmployeeEntity

    $touchedAttributes:=New collection
    $emp:=ds.Employee.get(725)
    $emp.firstName:=$emp.firstName //Même modifié avec la même valeur, l'attribut est considéré comme touché
    $emp.lastName:="Martin"
    $touchedAttributes:=$emp.touchedAttributes()
    //$touchedAttributes: ["firstName","lastName"]

    Exemple 2

     var $touchedAttributes : Collection
    var $emp : cs.EmployeeEntity
    var $company : cs.CompanyEntity

    $touchedAttributes:=New collection

    $emp:=ds.Employee.get(672)
    $emp.firstName:=$emp.firstName
    $emp.lastName:="Martin"

    $company:=ds.Company.get(121)
    $emp.employer:=$company

    $touchedAttributes:=$emp.touchedAttributes()

    //collection $touchedAttributes: ["firstName","lastName","employer","employerID"]

    Dans ce cas :

    • firstName and lastName have a storage kind
    • employer has a relatedEntity kind
    • employerID est la clé étrangère de l'entité reliée employer

    .unlock()

    Historique
    ReleaseModifications
    17Ajout

    .unlock() : Object

    ParamètresTypeDescription
    RésultatObject<-Objet statut

    Description

    The .unlock() function removes the pessimistic lock on the record matching the entity in the datastore and table related to its dataclass.

    For more information, please refer to Entity locking section.

    Un enregistrement est automatiquement déverrouillé lorsqu'il n'est plus référencé par aucune entité dans le process qui l'a verrouillé (par exemple : si le verrou est posé sur uniquement sur une référence locale d'une entité, l'entité et donc l'enregistrement sont déverrouillés lorsque le process se termine).

    Lorsqu'un enregistrement est verrouillé, il doit être déverrouillé depuis le process qui l'a verrouillé et via la référence d'entité sur laquelle le verrou a été posé. Par exemple :

     $e1:=ds.Emp.all()[0]
    $e2:=ds.Emp.all()[0]
    $res:=$e1.lock() //$res.success=true
    $res:=$e2.unlock() //$res.success=false
    $res:=$e1.unlock() //$res.success=true

    Result

    The object returned by .unlock() contains the following property:

    PropriétéTypeDescription
    successBooleanVrai si l'action unlock a été exécutée avec succès, Faux sinon. Si le déverrouillage est effectué sur une entité qui a été supprimée, sur un enregistrement non verrouillé ou sur un enregistrement verrouillé par un autre process ou une autre entité, success vaut Faux.

    Exemple

     var $employee : cs.EmployeeEntity
    var $status : Object

    $employee:=ds.Employee.get(725)
    $status:=$employee.lock()
    ... //processing
    $status:=$employee.unlock()
    If($status.success)
    ALERT("L'entité est déverrouillée")
    End if