Archivo Modulo 8 Gonzalo
Archivo Modulo 8 Gonzalo
Learning Objectives
By the end of this module, you will be able to:
• Delete objects
• Should it be possible for a training event to be deleted when people have already
registered for it?
• What should happen to a trainee’s registrations if the trainee is deleted from the
database?
We’ll get to delete behavior towards the end of this module. First we’ll make sure
that data being added to the app is valid. There are three methods of validating
data with Mendix:
Adding validation to the Domain Model means that every component, page, or
microflow in your project using that object must pass the validation check. If you
apply validation here, it’s applied everywhere
Microflows
Adding validation to microflows makes the validation rules more accessible and
visible for everyone. Those rules are also easily updated without impacting the
underlying domain model.
Pages
Adding validation to pages only applies on that page, not in other places. Also you
can only have one validation rule per field. A course title can’t be both required and
unique if you use a page validation.
Validation Rules
In the last lecture you considered a situation where a trainee’s email address is not
valid. Other things of that nature may occur, like a mistyped address or blank last
name. How can you prevent these rather simple mistakes with Mendix? That’s
where Validation Rules come in.
Type Description
The attribute should have a value that is unique compared to the values of this attribute in
Unique
For example: A course cannot have the same title as another course which is in the datab
The attribute value needs to be equal to a specified value or equal to the value of another
Equals
For example: When you have a form to change your password and you need to enter you
The attribute value needs to be in a range between specified values or between the value
Range
For example: The duration of a course needs to be a minimum of 1 day, but 10 days at th
The attribute needs to match a regular expression. A regular expression uses pattern rec
Regular expression
For example: The email address needs to be a valid email address (something@somethi
The attribute may have no more than the specified number of characters.
Maximum length
For example: An American zip code always has five characters, so when someone enters
• On a Page, with an input widget for the attribute: The end-user tried to
add an object to the database, using a page that has an input widget for the
attribute, but did not fill it out correctly. In that case an error message
appears underneath the input widget.
• On a Page, without an input widget for the attribute: The end-user tried
to add an object to the database, but the attribute that didn’t pass the check
doesn’t have an input widget on the page the end-user is currently looking
at. A pop-up message appears, with the error message in it.
• In a Microflow: A microflow attempts to commit the object to the database
but is stopped by validation. In that case an error message appears in the
log.
In each of the above cases the object is not committed to the database, preventing
incomplete or wrong information from ending up in the database.
Add Validation Rules to the Domain Model
Time to add validation rules to your Domain Model! Set the following story to
Running: As an administrator, I want data to be valid and consistent, so my
database doesn’t become messy.
Jimmy came up with the following validations for the LearnNow app:
ENTITY ATTRIBUTE V
COURSE Title R
Duration R
Price R
Description R
LOCATION Name R
Address R
TEACHER Name R
EmailAddress R
TRAINEE Name R
Address R
EmailAddress R
Trainer selection R
Course selection R
Location selection R
Let’s start by adding the first validation rule to the Course entity! The validation rule
is that Title is Required. That means that a Course can be stored in the Database if
and only if it has a title!
1. Open the Domain Model and double click on the Course entity to open its
properties.
2. The third tab is the Validation rules tab. Click it.
3. Let’s add the first validation rule: the title can’t be empty. Click New to
create a new validation rule.
4. Set the Attribute to Title, because this is the attribute you are creating a
validation rule for. The Rule is already on Required, so that can stay the
same.
5. Type a clear error message in the Error message text area.
6. Once you’re done click OK.
According to the second validation rule, the title also needs to be unique. This
means the same title can’t already be in the database. To add this second
validation rule to the title attribute, you need to create a new validation rule.
7. Click New to add the second validation rule to the title attribute.
8. Keep going until you’ve added all validation rules to the Course entity. Here
is an overview of them:
Take a look at your Domain Model. Do you see the green checkmarks that have
appeared behind the attribute names? This tells you that an attribute has one or
more validation rules applied to it.
You are probably wondering why you didn’t have to add any validation rules to the
TrainingEvent entity yet. Go to the next lecture to discover why that is.
Validation in Microflows
In the previous lecture you added validation rules to the Domain Model. You did that for
Course, Location, Teacher, and Trainee. The TrainingEvent also needed validation rules, but
you didn’t add these to the Domain Model. Let’s take another look at the validations Jimmy has
requested for events:
ENTITY ATTRIBUTE
TrainingEvent StartDate
ENTITY ATTRIBUTE
Trainer selection
Course selection
Location selection
Here you see that four validations are required. One of them is an attribute (StartDate) and the
other three are associations. Unlike attributes, associations can’t be validated in the Domain
Model. This is the primary limitation of Domain Model Validation Rules. You need to validate
associations either on pages or in a microflow. A microflow is the preferred option here. This is
because it’s more future-proof than page validation because it allows your app to scale more
easily. Microflows can be reused in multiple scenarios, but page validation will need to be
configured repeatedly any time a new page accesses the data being validated. There is also
no way to ensure that all pages concerning Training Events will validate them in the same way,
or even at all. Microflows make this process much easier to control.
Maybe you are wondering right now why you didn’t add the StartDate validation to the Domain
Model earlier. This is because your end-user only expects to have their actions validated once.
For example: say for a particular entity you validate some information in the Domain Model and
some in a microflow. The end user will have validation messages popping up at different times.
This is very confusing and frustrating for your end user. So, the moment you validate one
member (attribute or association) of an entity in a microflow, do all the other validations in that
microflow at the same time.
Now that you know that you are going to have to build a microflow for the validation process,
it’s time to figure out when this microflow should be triggered. Just like calculating the number
of registrations, you want to make sure Training Events are validated at the moment they are
added to the database, i.e., when Jimmy clicks the Save button on the Training Event NewEdit
page. This is going to require another custom Save button!
Before you get to work, let’s take a look at the desired end goal: The TrainingEvent_NewEdit
page with specific validation feedback messages underneath each input widget. Also, all
validation feedback messages are presented to the end-user in one go. Jimmy provided you
with a wireframe illustrating how he’d like to see this, and here’s how it will look in the running
app once complete:
• The StartDate, Course, Location and Teacher are required fields. They can’t be empty.
You don’t have to worry about the EndDate, because that field is filled automatically by
the EndDate calculation microflow.
• Each input widget (field) should get its own validation feedback message, shown
underneath the input widget. If you do this, the user will know which field they still need
to fill in and with what information.
• All these validation feedback messages need to be presented to the end-user at once,
so they don’t become frustrated with multiple rounds of corrections followed by more
error messages.
• Only when the TrainingEvent passes all validation checks can it be committed to the
database.
• After the TrainingEvent is committed (saved), the page needs to be closed. This will
make the app go back to the TrainingEvent_Overview page. If this doesn’t happen, the
end-user will be confused as they will think the training event hasn’t been saved! The
overview page also needs to be refreshed to show the new TrainingEvent information.
This should sound familiar because it’s exactly how the Registration save microflow
works too.
To complete all that, you need to create a microflow that will be triggered from the Save button,
add the validation checks, and make sure that feedback messages appear! You will see how
you can do all that in the following assignments.
PreviousNext
Create a Validation Microflow
Firstly, you need to create a microflow that will be triggered from the Save button:
1. Open the TrainingEvent_NewEdit page. This is a page with a data view that is
connected to the TrainingEvent entity. In the footer of the dataview, you will find the
default Save and Cancel buttons. Right click the Save button that is indicated below
and click Edit on click action.
The microflow has an input parameter of TrainingEvent. This is the TrainingEvent that is about
to be stored in the database. But before it is allowed to be committed to the database, it first
needs to pass the validation checks!
4. As always, start with the end result. That would be committing the TrainingEvent and
closing the page. Add these two activities to your microflow. Don’t forget to set Refresh
in Client to yes, as you want to have a relevant message appearing once the checks
performed in the microflow are done.
So far, you made the Save button trigger a simple microflow, but the microflow you created
doesn’t include any validation checks yet. See how you can build those checks in the following
assignment!
PreviousNext
Build Validation Checks
Approach the rest of this assignment step by step.
• After that, add the validation feedback messages to the members that are being checked.
• Once you’ve done that successfully, make sure to get all feedback messages back to the
end-user in one go.
You already know how to build checks: by using decisions. You could check that all fields have
been entered in one decision by using the following microflow expression:
$TrainingEvent/StartDate != empty AND
$TrainingEvent/MyFirstModule.TrainingEvent_Course != empty AND
$TrainingEvent/MyFirstModule.TrainingEvent_Location != empty AND
$TrainingEvent/MyFirstModule.TrainingEvent_Teacher != empty
• It makes the readability of the microflow poor. The microflow actually becomes more
difficult to interpret because you have to open the decision to see what it does. You also
need to read and interpret multiples lines of microflow expression. This is something you
should try to avoid.
• If you do all checks in one decision, it becomes impossible to add the validation feedback
messages underneath the specific input widgets. This is because you can’t differentiate
which fields have and have not passed the validation. To achieve this, you need to build
one decision per input widget.
1. Add four decisions to your microflow. Have each one check that its field is filled in. Make
sure to add a clear caption and to follow the ‘happy path’. In other words, make sure that
the outgoing true flow is the one that goes on to the commit activity and the false flow
goes to an end event. In the next lecture you will see how you can change these end
events into feedback messages.
1. Add a Validation feedback activity to the first false flow (the one coming out of the
decision that checks the StartDate).
• The Member is the input widget you want the validation message to appear
underneath. In this case, the StartDate.
• The Template is the message that will be shown to the user. Fill out a message that
will help your users understand what they need to do. In this case, “Please select a
start date”.
3. Click OK.
4. Repeat the previous steps to add validation feedback activities to each outgoing false
flow and set them up correctly.
At the end of this assignment, your microflow should look like this:
At this point the user will get multiple rounds of feedback. Because every time a check doesn’t
pass, the microflow goes down the false path and the app exits the microflow (via the end
event). It never reaches the next check! This behavior is very frustrating for the user. You need
to make sure that all checks are executed at once and the user immediately sees what they
still need to do to be able to save their training event. What you need is a way to go through all
the checks, even if the microflow goes down a false path. Learn more about how you can do
that in the next assignment!
PreviousNext
Can you predict what the problem is with the microflow in its current state? If you’re
not sure, try running your app and testing it.
The problem with the current solution is that even though the microflow goes
through all the checks, it will still commit the TrainingEvent even if it isn’t valid! How
can you still maintain one flow where you show all feedback messages back at
once, without committing the object at the end if it isn’t valid? You need a way to
record if the microflow went down a false path somewhere in the process. You can
do this by using a flag. A flag is a term for a true/false condition. It signals a go/no
go condition, like a railroad flagman indicating whether or not it’s safe for the train
to proceed.
This true/false flag sounds an awful lot like an attribute type you already know,
doesn’t it? That’s right, you can use a Boolean value! And the flag is
a variable that you can use to store that Boolean value.
Let’s continue with the assignment and add a flag to the microflow! The starting
value of this flag will be true. This is because you assume that the end-user did
what they were supposed to do, which is fill out every field of the form. If they didn’t
do that – causing the microflow to travel down the false path – the value of the
Boolean variable will be set to false.
4. Place a Create variable activity at the beginning of the microflow, directly after the
start event.
5. Open its properties. Leave the Data type as Boolean, set the value to true, and
change the variable name to something meaningful, like ValidTrainingEvent.
6. Now place a Change variable activity on the false path for the first decision. Select
the ValidTrainingEvent variable and set the value to false.
Did you know that instead of dragging and dropping the Change variable activity to
the flow, you can make use of MxAssist Logic Bot? Try changing the variable using
Logic Bot!
7. Press on this blue dot and you’ll get several suggestions. Choose Change
ValidTrainingEvent. This was easy, right?
8. Create all four change variables, either manually, with Logic Bot, or by
copying and pasting the first one you made. Each is identical so
copy/pasting is a fantastic way to save time and effort. Select the element(s)
you want to copy and use the Ctrl+c and then Ctrl+v keyboard shortcuts.
9. At the end of the validation checks, right before the microflow does the
commit, place a final decision. This decision will check whether the value of
the Boolean variable is still true.
• If yes, the TrainingEvent object passes all validation checks and can be committed.
• If not, you know that one or more checks didn’t pass and the microflow needs to
exit without committing the object. At that point the end-user will be presented with
the validation feedback messages.
Here is what your microflow will look like at the end of this assignment:
Run your app and test the functionality. Does it work as expected? If not, go
through this module again to see if you followed the instructions step by step. If
yes, go ahead and commit your work to the Team Server and set the story to
Done!
Deleting Objects
So far in this module, you have learned how to make sure that the data that enters your
database is consistent and valid. In the same way, you need to make sure you have control
over what data is deleted from your database!
In the Developer Portal, set the next user story to In Progress: As an administrator, I want to
be able to delete training events that don’t have registrations, so I can’t accidentally
delete a training event that people have already paid for to attend.
According to that user story, Jimmy wants to be able to delete training events, but only if no
one has registered for that event yet. Otherwise he could get some unhappy faces if trainees
have already paid to attend a certain training event and then the event was canceled all of a
sudden. Or trainees would show up at the event, but of course there would be no training
because the event had been canceled.
Therefore, you need to make sure that when the user tries to delete an object, the app
prevents this if there are any objects associated with it. This can be accomplished with a
setting in the Domain model, specifically in the properties of an entity. The behavior you want
to activate in this case is called prevention of delete, and it is one of the options in the
following image:
Let’s unpack this window a little bit. The first section, multiplicity, shows you what type an
association is.
The next two options show you the delete behavior settings. In other words, what should
happen when you delete one of the associated objects. In the example, when you want to
delete the ‘TrainingEvent’ object, you have three options:
• Keep ‘Registration’ object(s). This means that you will be able to delete the training
event and all the registrations that belong to it will stay in the system. This is also
called no predefinition and is the default setting for delete behavior.
• Delete ‘Registration’ object(s) as well. This means the training event and all
registrations that belong to it will be deleted from the system. This type of delete
behavior is called cascading delete.
Tip
If you get a system error message when you try to delete an object in an app, take a look at
your Domain Model. Perhaps somewhere down the line prevention of delete is triggered and
you forgot to fill out a custom error message.
In the following assignments, you will provide Jimmy with the ability to delete a training event.
Let’s get started!
PreviousNext
4. The button is now placed next to the existing button. Double click the button
to open its properties. Empty the caption and select the trash-can icon. Set
the button style to Danger so it gets a red color.
5. Also in the button’s properties, set Close page to No. That means that the
TrainingEvent Overview page will stay open when you delete a training event.
6. Click OK.
Well done! You set up the Delete button that will delete a training event. Continue
to the next assignment to configure the delete behavior. You will prevent Training
Events to be deleted if some participants have already registered for those events!
1. You manage delete behavior in the Domain Model, so go ahead and open
it.
2. Double click on the Registration_TrainingEvent association to open its
properties. The following window will open:
Do you see that blue border that has appeared around the association? This tells
you that this association has prevention of delete applied to it.
6. Congratulations! Jimmy can now cancel scheduled training events. He will be really
happy with that! Commit your newly created functionality to the Team Server and
set the story to Done. Don’t forget to select the story as the related user story
during the commit!
Cascading Delete
Another thing that Jimmy wants to be able to delete is the Trainees and their
information from the system. When they are deleted, all the registrations that
belong to them should be deleted as well. This type of delete behavior is
called cascading delete. That means that when one object is deleted, all the
associated objects are deleted automatically as well. You can see whether an
association has cascading delete applied to it by the red border that appears
around the association (as shown in the image below).
4. Make sure to run and test your solution! Once you are satisfied with
it, Commit your work to the Team Server and set the story to Done!
Congratulations! You have managed to make sure that the data in your database is
always consistent and valid! In the next lecture you will learn how to set up the
security of your app. In that way, your data will not only be correct, but will also be
safe!
Summary
Congratulations! You now have an app that is not only user friendly and effective,
but also makes sure that the data that gets in or out of your database is consistent
and valid!
In the next lecture you will learn how to set up the security of your app. In that way,
your data will not only be correct, but will also be safe!
In the Resources tab, you will find the mpk with the solution of module 8.
ESPAÑOL
Objetivos de aprendizaje
Al final de este módulo, podrá:
• ¿Qué debería pasar con los registros de un alumno si se elimina al alumno de la base
de datos?
Agregar validación al modelo de dominio significa que cada componente, página o microflujo
de su proyecto que utilice ese objeto debe pasar la verificación de validación. Si aplica la
validación aquí, se aplica en todas partes.
Microflujos
Agregar validación a los microflujos hace que las reglas de validación sean más accesibles y
visibles para todos. Esas reglas también se actualizan fácilmente sin afectar el modelo de
dominio subyacente.
paginas
Agregar validación a las páginas solo se aplica en esa página, no en otros lugares. Además,
solo puedes tener una regla de validación por campo. El título de un curso no puede ser
obligatorio y único si utiliza una validación de página.
AnteriorPróximo
Reglas de validación
En la última conferencia consideró una situación en la que la dirección de correo electrónico
de un alumno no es válida. Pueden ocurrir otras cosas de esa naturaleza, como una dirección
mal escrita o un apellido en blanco. ¿Cómo puedes prevenir estos errores bastante simples
con Mendix? Ahí es donde entran las reglas de validación.
El atributo debe tener un valor que sea único en comparación con los valores de este atributo en to
Único
Por ejemplo: un curso no puede tener el mismo título que otro curso que ya esté en la base de dato
El valor del atributo debe ser igual a un valor especificado o igual al valor de otro atributo del mism
igual
Por ejemplo: cuando tienes un formulario para cambiar tu contraseña y necesitas ingresar tu nueva
El valor del atributo debe estar en un rango entre valores especificados o entre los valores de otros
Rango
Por ejemplo: La duración de un curso debe ser de un mínimo de 1 día, pero como máximo de 10 día
El atributo debe coincidir con una expresión regular . Una expresión regular utiliza el reconocimient
Expresión regular
Por ejemplo: la dirección de correo electrónico debe ser una dirección de correo electrónico válida
• En una página, con un widget de entrada para el atributo: el usuario final intentó
agregar un objeto a la base de datos, utilizando una página que tiene un widget de
entrada para el atributo, pero no lo completó correctamente. En ese caso, aparece un
mensaje de error debajo del widget de entrada.
• En una página, sin un widget de entrada para el atributo: el usuario final intentó
agregar un objeto a la base de datos, pero el atributo que no pasó la verificación no
tiene un widget de entrada en la página en la que se encuentra el usuario final.
actualmente mirando. Aparece un mensaje emergente con el mensaje de error.
En cada uno de los casos anteriores, el objeto no se confirma en la base de datos, lo que evita
que información incompleta o incorrecta termine en la base de datos.
AnteriorPróximo
ENTIDAD ATRIBUTO
CURSO Título
Duración
Precio
Descripción
UBICACIÓN Nombre
DIRECCIÓN
MAESTRO Nombre
APRENDIZ Nombre
DIRECCIÓN
Selección de entrenador
Selección de cursos
Selección de ubicación
1. Abra el modelo de dominio y haga doble clic en la entidad del curso para abrir sus
propiedades.
Según la segunda regla de validación, el título también debe ser único. Esto significa que el
mismo título no puede estar ya en la base de datos. Para agregar esta segunda regla de
validación al atributo de título, debe crear una nueva regla de validación.
7. Haga clic en Nuevo para agregar la segunda regla de validación al atributo del título.
8. Continúe hasta que haya agregado todas las reglas de validación a la entidad Curso.
Aquí hay una descripción general de ellos:
Eche un vistazo a su modelo de dominio. ¿Ves las marcas de verificación verdes que
aparecieron detrás de los nombres de los atributos? Esto le indica que un atributo tiene una o
más reglas de validación aplicadas.
Probablemente se esté preguntando por qué no tuvo que agregar ninguna regla de validación
a la entidad TrainingEvent todavía. Vaya a la siguiente conferencia para descubrir por qué es
así.
AnteriorPróximo
Validación en Microflujos
En la lección anterior agregaste reglas de validación al modelo de dominio. Hiciste eso para
Curso, Ubicación, Profesor y Aprendiz. TrainingEvent también necesitaba reglas de validación,
pero no las agregó al modelo de dominio. Echemos otro vistazo a las validaciones que Jimmy
solicitó para los eventos:
ENTIDAD ATRIBUTO
Selección de entrenador
Selección de cursos
ENTIDAD ATRIBUTO
Selección de ubicación
Aquí ves que se requieren cuatro validaciones. Uno de ellos es un atributo (StartDate) y los
otros tres son asociaciones. A diferencia de los atributos, las asociaciones no se pueden
validar en el modelo de dominio. Ésta es la principal limitación de las reglas de validación del
modelo de dominio. Debe validar las asociaciones en páginas o en un microflujo. Un microflujo
es la opción preferida aquí. Esto se debe a que está más preparado para el futuro que la
validación de páginas porque permite que su aplicación escale más fácilmente. Los microflujos
se pueden reutilizar en múltiples escenarios, pero la validación de la página deberá
configurarse repetidamente cada vez que una nueva página acceda a los datos que se están
validando. Tampoco hay forma de garantizar que todas las páginas relacionadas con Eventos
de capacitación las validen de la misma manera, o incluso que no las validen en absoluto. Los
microflujos hacen que este proceso sea mucho más fácil de controlar.
Quizás ahora se esté preguntando por qué no agregó anteriormente la validación de fecha de
inicio al modelo de dominio. Esto se debe a que su usuario final solo espera que sus acciones
se validen una vez. Por ejemplo: digamos que para una entidad en particular valida cierta
información en el modelo de dominio y otra en un microflujo. El usuario final verá mensajes de
validación apareciendo en diferentes momentos. Esto es muy confuso y frustrante para el
usuario final. Entonces, en el momento en que validas un miembro (atributo o asociación) de
una entidad en un microflujo, realiza todas las demás validaciones en ese microflujo al mismo
tiempo.
Ahora que sabe que tendrá que crear un microflujo para el proceso de validación, es hora de
determinar cuándo se debe activar este microflujo. Al igual que al calcular el número de
registros, desea asegurarse de que los eventos de capacitación se validen en el momento en
que se agregan a la base de datos, es decir, cuando Jimmy hace clic en el botón Guardar en
la página NewEdit del evento de capacitación. ¡Esto requerirá otro botón Guardar
personalizado!
Analicemos eso:
Para completar todo eso, debe crear un microflujo que se activará desde el botón Guardar,
agregar las comprobaciones de validación y asegurarse de que aparezcan mensajes de
comentarios. Verás cómo puedes hacer todo eso en las siguientes tareas.
AnteriorPróximo
1. Abra la página TrainingEvent_NewEdit. Esta es una página con una vista de datos que
está conectada a la entidad TrainingEvent. En el pie de página de la vista de datos,
encontrará los botones predeterminados Guardar y Cancelar . Haga clic derecho en
el botón Guardar que se indica a continuación y haga clic en Editar al hacer clic en
la acción .
4. Como siempre, empieza por el resultado final. Eso sería confirmar el TrainingEvent y
cerrar la página. Añade estas dos actividades a tu microflujo. No olvide
configurar Actualizar en Cliente en sí , ya que desea que aparezca un mensaje
relevante una vez que se realicen las comprobaciones realizadas en el microflujo.
AnteriorPróximo
Ya sabes cómo crear controles: utilizando decisiones. Puede verificar que todos
los campos se hayan ingresado en una decisión usando la siguiente expresión de
microflujo: $
TrainingEvent/StartDate != vacío AND
$TrainingEvent/MyFirstModule.TrainingEvent_Course != vacío AND
$TrainingEvent/MyFirstModule.TrainingEvent_Location != vacío AND
$TrainingEvent/ MyFirstModule.TrainingEvent_Teacher! = vacío
1. Agregue cuatro decisiones a su microflujo. Haga que cada uno verifique que su
campo esté completo. Asegúrese de agregar un título claro y de seguir el "camino
feliz". En otras palabras, asegúrese de que el flujo verdadero saliente sea el que
continúa con la actividad de confirmación y el flujo falso vaya a un evento final. En
la próxima conferencia verás cómo puedes convertir estos eventos finales en
mensajes de retroalimentación.
• El Miembro es el widget de entrada debajo del cual desea que aparezca el mensaje
de validación. En este caso, la fecha de inicio .
En este punto, el usuario recibirá múltiples rondas de comentarios. Porque cada vez que una
verificación no pasa, el microflujo sigue el camino falso y la aplicación sale del microflujo (a
través del evento final). ¡Nunca llega al siguiente cheque! Este comportamiento es muy
frustrante para el usuario. Debe asegurarse de que todas las comprobaciones se ejecuten a la
vez y que el usuario vea inmediatamente lo que aún debe hacer para poder guardar su evento
de capacitación. Lo que necesita es una forma de realizar todas las comprobaciones, incluso
si el microflujo sigue un camino falso. ¡Obtenga más información sobre cómo puede hacerlo
en la próxima tarea!
AnteriorPróximo
7. Pulsa sobre este punto azul y obtendrás varias sugerencias. Elija Cambiar
ValidTrainingEvent. Esto fue fácil, ¿verdad?
8. Cree las cuatro variables de cambio, ya sea manualmente, con Logic Bot, o
copiando y pegando la primera que creó. Cada uno es idéntico, por lo que
copiar y pegar es una manera fantástica de ahorrar tiempo y esfuerzo.
Seleccione los elementos que desea copiar y use los atajos de
teclado Ctrl+c y luego Ctrl+v .
9. Al final de las comprobaciones de validación, justo antes de que el
microflujo se comprometa, tome una decisión final. Esta decisión
comprobará si el valor de la variable booleana sigue siendo verdadero.
Eliminar objetos
Hasta ahora, en este módulo, ha aprendido cómo asegurarse de que los datos que
ingresan a su base de datos sean consistentes y válidos. De la misma manera,
debes asegurarte de tener control sobre qué datos se eliminan de tu base de
datos.
En el Portal del desarrollador, establezca la siguiente historia de usuario en En
progreso: como administrador, quiero poder eliminar eventos de capacitación
que no tienen registros, para no poder eliminar accidentalmente un evento
de capacitación por el que la gente ya haya pagado. para asistir.
Si recibe un mensaje de error del sistema cuando intenta eliminar un objeto en una
aplicación, consulte su modelo de dominio. Quizás en algún momento se active la
prevención de eliminación y olvidó completar un mensaje de error personalizado.
4. El botón ahora se coloca al lado del botón existente. Haga doble clic en el botón para
abrir sus propiedades. Vacía el título y selecciona el ícono de la papelera . Establezca
el estilo del botón en Peligro para que adquiera un color rojo.
5. También en las propiedades del botón, establezca Cerrar página en No. Eso significa
que la página Descripción general de TrainingEvent permanecerá abierta cuando
elimine un evento de capacitación.
6. Haga clic en Aceptar .
¡Bien hecho! Usted configura el botón Eliminar que eliminará un evento de capacitación.
Continúe con la siguiente tarea para configurar el comportamiento de eliminación. ¡Evitará que
se eliminen los eventos de capacitación si algunos participantes ya se han registrado para
esos eventos!
AnteriorPróximo
¿Ves ese borde azul que ha aparecido alrededor de la asociación? Esto le indica que esta
asociación tiene aplicada la prevención de eliminación .
Eliminación en cascada
Otra cosa que Jimmy quiere poder eliminar son los aprendices y su información
del sistema. Cuando se eliminen, también se deberán eliminar todos los registros
que les pertenecen. Este tipo de comportamiento de eliminación se
denomina eliminación en cascada . Eso significa que cuando se elimina un
objeto, todos los objetos asociados también se eliminan automáticamente. Puede
ver si a una asociación se le ha aplicado eliminación en cascada mediante el
borde rojo que aparece alrededor de la asociación (como se muestra en la imagen
a continuación).
4. ¡Asegúrese de ejecutar y probar su solución! Una vez que esté satisfecho con
él, envíe su trabajo al Team Server y configure la historia como Listo .
¡Felicidades! ¡Ha logrado asegurarse de que los datos en su base de datos sean siempre
consistentes y válidos! En la próxima conferencia aprenderá cómo configurar la seguridad de
su aplicación. De esa manera, tus datos no sólo serán correctos, ¡sino que también estarán
seguros!
AnteriorPróximo
Resumen
¡Felicidades! Ahora tiene una aplicación que no sólo es fácil de usar y efectiva, sino que
también garantiza que los datos que entran o salen de su base de datos sean consistentes y
válidos.
AnteriorPróximo