0% found this document useful (0 votes)
18 views38 pages

Archivo Modulo 8 Gonzalo

Uploaded by

yarlei.luna117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views38 pages

Archivo Modulo 8 Gonzalo

Uploaded by

yarlei.luna117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

INGLES

Learning Objectives
By the end of this module, you will be able to:

• Explain the importance of having valid and consistent data

• Add validation rules to the domain model

• Build validation microflows

• Configure validation checks using decisions

• Add validation feedback messages

• Merge multiple flows

• Delete objects

• Configure specialized delete behavior


PreviousNext
The Importance of Having Valid and Consistent
Data
The LearnNow Training Management app is almost complete! You have set up a
Domain Model which ensures all relevant data is available in the app. You have
built beautiful and user-friendly pages and features that allow Jimmy to easily
manage his company. You have also created microflows that help Jimmy work
more efficiently. Now it’s time to make sure that the information in the app is valid
and consistent.
Suppose a user is creating a new course and clicks Save without filling out any
details. The object is added to the database as an empty record, so there will be a
new course in the system, but it doesn’t have a title or description! Something else
that is possible right now is that trainees can be added to the system without a
(valid) email address, (for example: [email protected]). Jimmy can’t then contact them if
he needs to. To avoid these inconvenient situations, you need to make sure that all
data that’s added to the system meets the rules that Jimmy has provided you with.
In other words, you need to make sure data that is added to the database is valid.
As you can see in the description of the next user story, it is important for Jimmy
that all fields for a course are filled in before someone can add it to the database
and that each course has a unique title.
Currently it isn’t possible to delete data at all, so that functionality needs to be
added too. Jimmy should at least be able to delete training events. But what should
happen when data is deleted from the app? This is called delete behavior.
If you don’t set up the delete behavior correctly, you run the risk of data being
deleted when it shouldn’t be, which could cause major problems for Jimmy.
Another risk of not having delete behavior set up correctly is that when data is
deleted, other objects with a connection to this data become meaningless. In this
case they should also be deleted automatically, to keep the database clean.
Think about the following questions:

• 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:

Validation Rules in the Domain Model

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.

Adding Validation Rules


Validation rules are conditions that must be met before an object is stored in the
database. They are applied to attributes in the Domain Model. When you add a
validation rule, you can also enter a custom error message that will be shown when
the validation rule is not matched.
Types of Validation Rules
There are several types of validation rules that you can apply to attributes in the
Domain Model:

Type Description

The attribute needs to have a value. It cannot be empty.


Required
For example: The description of a course can’t be empty.

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

What Happens when an Object isn’t Valid?


So, what happens if the object doesn’t pass the validation check? Well, depending
on where in the app the validation was triggered, there are three possible results:

• 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

TRAINING EVENT StartDate 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:

9. Add the rest of the validation rules as well:

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:

Let’s break that down:

• 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.

2. Change the On click from Save changes to Call a microflow.


3. The microflow you need does not exist yet, so in the next screen click New. A good
name for this microflow would be ACT_TrainingEvent_SaveValidate. Complete the
creation of the microflow and open it.

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.

Here is what the microflow should look like:

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.

• Firstly, build all the necessary checks.

• 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

However, there are two issues with this approach:

• 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.

Here is what your microflow should look like now:

Here is an example of how the decisions should be


configured: Add Validation Feedback Messages
The next step is to add the validation feedback messages. These let the user know a validation
check hasn’t passed: when the microflow travels down a false path. To add the validation
feedback messages to your microflow:

1. Add a Validation feedback activity to the first false flow (the one coming out of the
decision that checks the StartDate).

2. Configure the validation feedback:


• The Variable is the object you are validating (in this case the TrainingEvent).

• 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

Merge Multiple Flows


A decision can only have one incoming flow. This means you can’t directly make
the false flow continue to the next decision. There is a component you can use for
this though: the merge.
The merge is the red diamond shaped component in microflows. It’s used to go
from multiple branches back to one single flow.

Here is what you need to do to the microflow:

1. Delete the end events at the bottom of each false path.


2. Add a merge after each decision.
3. Drag a flow from the validation feedback activities to the merges, just like in the
next image.

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.

• Delete ‘TrainingEvent’ object only if it is not associated with ‘Registration’


object(s). This means that the training event can only be deleted if it doesn’t have any
registrations connected to it yet. This type of delete behavior is called prevention of
delete. When selecting this, you also get the option to show an error message to the
end-user, informing them why they cannot delete a certain object.

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

Add Delete Button


Firstly, let’s make sure that there is a delete button in place. Jimmy wants to be
able to delete training events, so you’ll need a delete button on the
TrainingEvent_Overview page.
To do that:

1. Open the TrainingEvent_Overview page in Mendix Studio Pro.


2. In the Toolbox, look for the Delete button.
3. Place it in the list view item, to the right of the > button.

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!

Add Delete Behavior: Prevention of Delete


Awesome, the button is done! Now it’s time to set up the delete behavior. Jimmy
wants training events to be deleted only when there aren’t any registrations
connected to them yet.

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:

3. Under On delete of ‘TrainingEvent’ select Delete ‘TrainingEvent’ object


only if it is not associated with ‘Registration’ object(s). Leave the other
options as they are set by default.
4. Add an error message in the text area which appears under Delete
‘TrainingEvent’ object only if it is not associated with ‘Registration’
object(s). This error message is shown to the end-user when the deletion is
prevented. Perhaps something like this: Sorry, this training event can’t be
deleted. People have already registered for it!
5. Click OK.

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).

Delete Objects with Cascading Delete


You can build this functionality using the same approach as in the previous
assignment. Here are the steps that you will need to take:

1. Set the next user story to Running: As an administrator, I want to be able


to delete Trainees and all their Registrations, so that I can remove
them from the system if they no longer wish to be a LearnNow student.
2. Add a Delete button on the Trainee_Overview page. Make the button
stand out by giving it a nice icon and color. If you need help with that step
you can refer to lecture ‘8.4.1 Add Delete button’. If you want to save
yourself some time, you can also copy and past the delete button from the
last exercise here. They both do the same thing! Here is what your button
should look like at the end:

3. Add the delete behavior on the Registration_Trainee association in the


Domain Model. If you need help with that step you can refer to lecture ‘8.5.2
Add Delete Behavior: Prevention of Delete’. Note that you need to
select Delete ‘Registration’ Object(s) as well this time!

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á:

• Explicar la importancia de tener datos válidos y consistentes.


• Agregar reglas de validación al modelo de dominio
• Construir microflujos de validación
• Configurar comprobaciones de validación mediante decisiones
• Agregar mensajes de comentarios de validación
• Fusionar múltiples flujos
• Eliminar objetos
• Configurar el comportamiento de eliminación especializado
La importancia de tener datos válidos y consistentes
¡La aplicación LearnNow Training Management está casi completa! Ha configurado un modelo
de dominio que garantiza que todos los datos relevantes estén disponibles en la aplicación. Ha
creado páginas y funciones hermosas y fáciles de usar que le permiten a Jimmy administrar
fácilmente su empresa. También ha creado microflujos que ayudan a Jimmy a trabajar de
manera más eficiente. Ahora es el momento de asegurarse de que la información de la
aplicación sea válida y coherente.
Supongamos que un usuario está creando un nuevo curso y hace clic en Guardar sin
completar ningún detalle. El objeto se agrega a la base de datos como un registro vacío, por lo
que habrá un nuevo curso en el sistema, ¡pero no tiene título ni descripción! Otra cosa que es
posible ahora es que los alumnos se puedan agregar al sistema sin una dirección de correo
electrónico (válida) (por ejemplo: [email protected]) . Entonces Jimmy no puede contactarlos si
es necesario. Para evitar estas situaciones inconvenientes, debe asegurarse de que todos los
datos que se agregan al sistema cumplan con las reglas que Jimmy le proporcionó. En otras
palabras, debe asegurarse de que los datos que se agregan a la base de datos sean válidos .
Como puede ver en la descripción de la siguiente historia de usuario, para Jimmy es
importante que todos los campos de un curso se completen antes de que alguien pueda
agregarlo a la base de datos y que cada curso tenga un título único.
Actualmente no es posible eliminar ningún dato, por lo que también es necesario agregar esa
funcionalidad. Jimmy al menos debería poder eliminar eventos de entrenamiento. Pero, ¿qué
debería pasar cuando se eliminan datos de la aplicación? Esto se llama comportamiento de
eliminación.
Si no configura el comportamiento de eliminación correctamente, corre el riesgo de que los
datos se eliminen cuando no deberían, lo que podría causar problemas importantes a Jimmy.
Otro riesgo de no tener configurado correctamente el comportamiento de eliminación es que
cuando se eliminan datos, otros objetos con una conexión con estos datos dejan de tener
sentido. En este caso también deberían eliminarse automáticamente, para mantener limpia la
base de datos.
Piensa en las siguientes preguntas:
• ¿Debería ser posible eliminar un evento de formación cuando las personas ya se
hayan registrado?

• ¿Qué debería pasar con los registros de un alumno si se elimina al alumno de la base
de datos?

Eliminaremos el comportamiento hacia el final de este módulo. Primero nos aseguraremos de


que los datos que se agregan a la aplicación sean válidos. Hay tres métodos para validar
datos con Mendix:

Reglas de validación en el modelo de dominio

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.

Agregar reglas de validación


Las reglas de validación son condiciones que deben cumplirse antes de que un objeto se
almacene en la base de datos. Se aplican a atributos en el modelo de dominio. Cuando
agrega una regla de validación, también puede ingresar un mensaje de error personalizado
que se mostrará cuando la regla de validación no coincida.

Tipos de reglas de validación


Existen varios tipos de reglas de validación que puede aplicar a los atributos en el modelo de
dominio:
Tipo Descripción

El atributo debe tener un valor. No puede estar vacío.


Requerido
Por ejemplo: La descripción de un curso no puede estar vacía.

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

El atributo no puede tener más que el número de caracteres especificado.


Longitud máxima
Por ejemplo: un código postal estadounidense siempre tiene cinco caracteres, por lo que cuando al

¿Qué sucede cuando un objeto no es válido?


Entonces, ¿qué pasa si el objeto no pasa la verificación de validación? Bueno, dependiendo
de en qué parte de la aplicación se activó la validación, hay tres resultados posibles:

• 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 un microflujo: un microflujo intenta enviar el objeto a la base de datos, pero la


validación lo detiene. En ese caso aparece un mensaje de error en el registro.

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

Agregar reglas de validación al modelo de dominio


¡Es hora de agregar reglas de validación a su modelo de dominio! Establezca la siguiente
historia en Ejecución: Como administrador, quiero que los datos sean válidos y
consistentes, para que mi base de datos no se ensucie .
A Jimmy se le ocurrieron las siguientes validaciones para la aplicación LearnNow:

ENTIDAD ATRIBUTO

CURSO Título

Duración

Precio

Descripción

UBICACIÓN Nombre

DIRECCIÓN

MAESTRO Nombre

Dirección de correo electrónico

APRENDIZ Nombre

DIRECCIÓN

Dirección de correo electrónico

EVENTO DE FORMACIÓN Fecha de inicio

Selección de entrenador

Selección de cursos

Selección de ubicación

¡Comencemos agregando la primera regla de validación a la entidad Curso! La regla de


validación es que el título es obligatorio. ¡Eso significa que un curso puede almacenarse en la
base de datos si y sólo si tiene un título!

1. Abra el modelo de dominio y haga doble clic en la entidad del curso para abrir sus
propiedades.

2. La tercera pestaña es la pestaña Reglas de validación . Pinchalo.


3. Agreguemos la primera regla de validación: el título no puede estar vacío. Haga clic
en Nuevo para crear una nueva regla de validación.
4. Establezca el Atributo en Título , porque este es el atributo para el que está creando
una regla de validación. La regla ya está en Required , por lo que puede permanecer
igual.
5. Escriba un mensaje de error claro en el área de texto del mensaje de error .
6. Una vez que haya terminado, haga clic en Aceptar .

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:

9. Agregue también el resto de las reglas de validación:

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

Evento de formación Fecha de inicio

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!

Antes de comenzar a trabajar, echemos un vistazo al objetivo final deseado: la página


TrainingEvent_NewEdit con mensajes de comentarios de validación específicos debajo de
cada widget de entrada. Además, todos los mensajes de comentarios de validación se
presentan al usuario final de una sola vez. Jimmy le proporcionó una estructura alámbrica que
ilustra cómo le gustaría ver esto, y así es como se verá en la aplicación en ejecución una vez
completada:

Analicemos eso:

• La fecha de inicio, el curso, la ubicación y el profesor son campos obligatorios. No


pueden estar vacíos. No tiene que preocuparse por EndDate, porque ese campo se
completa automáticamente mediante el microflujo de cálculo de EndDate.

• Cada widget de entrada (campo) debe recibir su propio mensaje de comentarios de


validación , que se muestra debajo del widget de entrada. Si haces esto, el usuario
sabrá qué campo le falta por rellenar y con qué información.
• Todos estos mensajes de comentarios de validación deben presentarse al usuario final
a la vez, para que no se sienta frustrado con múltiples rondas de correcciones
seguidas de más mensajes de error.

• Solo cuando TrainingEvent pasa todas las comprobaciones de validación se puede


enviar a la base de datos.

• Una vez confirmado (guardado) el TrainingEvent, es necesario cerrar la página. Esto


hará que la aplicación vuelva a la página TrainingEvent_Overview. Si esto no sucede,
el usuario final se confundirá porque pensará que el evento de capacitación no se ha
guardado. La página de descripción general también debe actualizarse para mostrar la
nueva información de TrainingEvent. Esto debería resultarle familiar porque así es
exactamente como también funciona el microflujo para guardar registros.

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

Crear un microflujo de validación


En primer lugar, debe crear un microflujo que se activará desde el botón Guardar:

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 .

2. Cambie Al hacer clic de Guardar cambios a Llamar a un microflujo .


3. El microflujo que necesita aún no existe, así que en la siguiente pantalla haga clic
en Nuevo . Un buen nombre para este microflujo
sería ACT_TrainingEvent_SaveValidate . Complete la creación del microflujo y
ábralo.

El microflujo tiene un parámetro de entrada de TrainingEvent. Este es el TrainingEvent que


está a punto de almacenarse en la base de datos. Pero antes de que se le permita enviarlo a
la base de datos, ¡primero debe pasar las comprobaciones de validació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.

Así es como debería verse el microflujo:


Hasta ahora, hizo que el botón Guardar activara un microflujo simple, pero el microflujo que
creó aún no incluye ninguna verificación de validación. ¡Vea cómo puede crear esos controles
en la siguiente tarea!

AnteriorPróximo

Verificaciones de validación de compilación


Aborde el resto de esta tarea paso a paso.

• En primer lugar, cree todos los controles necesarios.


• Después de eso, agregue los mensajes de comentarios de validación a los
miembros que se están verificando.
• Una vez que lo haya hecho correctamente, asegúrese de enviar todos los
mensajes de comentarios al usuario final de una sola vez.

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

Sin embargo, hay dos problemas con este enfoque:

• Empobrece la legibilidad del microflujo. En realidad, el microflujo se vuelve más


difícil de interpretar porque hay que abrir la decisión para ver qué hace. También
es necesario leer e interpretar varias líneas de expresión de microflujos. Esto es
algo que debes intentar evitar.
• Si realiza todas las comprobaciones en una sola decisión, resulta imposible
agregar los mensajes de comentarios de validación debajo de los widgets de
entrada específicos. Esto se debe a que no se puede diferenciar qué campos han
pasado la validación y qué no. Para lograr esto, necesita crear una decisión por
widget de entrada.

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.

Así es como debería verse su microflujo ahora:


A continuación se muestra un ejemplo de cómo se deben configurar las
decisiones:

Agregar mensajes de comentarios de validación


El siguiente paso es agregar los mensajes de comentarios de validación. Estos le permiten al
usuario saber que no se ha pasado una verificación de validación: cuando el microflujo viaja
por un camino falso. Para agregar los mensajes de comentarios de validación a su microflujo:

1. Agregue una actividad de retroalimentación de Validación al primer flujo falso (el


que surge de la decisión que verifica la Fecha de Inicio).

2. Configure los comentarios de validación:

• La Variable es el objeto que estás validando (en este caso el TrainingEvent) .

• 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 .

• La Plantilla es el mensaje que se mostrará al usuario. Complete un mensaje que


ayudará a sus usuarios a comprender lo que deben hacer. En este caso, "Seleccione
una fecha de inicio".

3. Haga clic en Aceptar .


4. Repita los pasos anteriores para agregar actividades de retroalimentación de
validación a cada flujo falso saliente y configurarlas correctamente.

Al final de esta tarea, su microflujo debería verse así:

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

Fusionar múltiples flujos


Una decisión sólo puede tener un flujo entrante. Esto significa que no puede hacer
que el flujo falso continúe directamente hasta la siguiente decisión. Sin embargo,
hay un componente que puedes usar para esto: el merge .
La fusión es el componente rojo con forma de diamante en los microflujos. Se
utiliza para pasar de varias ramas a un solo flujo.

Esto es lo que debe hacer con el microflujo:

1. Elimine los eventos finales en la parte inferior de cada ruta falsa.


2. Agregue una combinación después de cada decisión.
3. Arrastre un flujo desde las actividades de retroalimentación de validación a las
fusiones, como en la siguiente imagen.

¿Puedes predecir cuál es el problema con el microflujo en su estado actual? Si no


está seguro, intente ejecutar su aplicación y probarla.
El problema con la solución actual es que aunque el microflujo pasa por todas las
comprobaciones, seguirá confirmando el TrainingEvent incluso si no es válido.
¿Cómo se puede seguir manteniendo un flujo en el que se muestran todos los
mensajes de comentarios a la vez, sin confirmar el objeto al final si no es válido?
Necesita una forma de registrar si el microflujo siguió un camino falso en algún
momento del proceso. Puedes hacer esto usando una bandera . Una bandera es
un término para una condición verdadero/falso. Señala una condición de
avance/no avance, como un abanderado de ferrocarril que indica si es seguro o no
que el tren avance.
Esta bandera verdadero/falso se parece muchísimo a un tipo de atributo que ya
conoces, ¿no es así? Así es, ¡puedes usar un valor booleano ! Y la bandera es
una variable que puedes usar para almacenar ese valor booleano.
¡Continuemos con la tarea y agreguemos una bandera al microflujo! El valor inicial
de esta bandera será verdadero. Esto se debe a que se supone que el usuario
final hizo lo que se suponía que debía hacer, que es completar todos los campos
del formulario. Si no lo hicieron, lo que provocó que el microflujo viajara por el
camino falso, el valor de la variable booleana se establecerá en falso .

4. Coloque una actividad Crear variable al comienzo del microflujo, directamente


después del evento de inicio.
5. Abre sus propiedades. Deje el tipo de datos como booleano , establezca el valor
en verdadero y cambie el nombre de la variable a algo significativo,
como ValidTrainingEvent .
6. Ahora coloque una actividad Cambiar variable en la ruta falsa para la primera
decisión. Seleccione la variable ValidTrainingEvent y establezca el valor
en falso .

¿Sabías que en lugar de arrastrar y soltar la actividad Cambiar variable en el flujo,


puedes utilizar MxAssist Logic Bot? ¡Intenta cambiar la variable usando Logic Bot!

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.

• En caso afirmativo, el objeto TrainingEvent pasa todas las comprobaciones de


validación y puede confirmarse.
• De lo contrario, sabrá que una o más comprobaciones no pasaron y que el
microflujo debe salir sin confirmar el objeto. En ese momento, se presentarán al
usuario final los mensajes de comentarios de validación.

Así es como se verá su microflujo al final de esta tarea:

Ejecute su aplicación y pruebe la funcionalidad. ¿Funciona como se esperaba? De


lo contrario, revise este módulo nuevamente para ver si siguió las instrucciones
paso a paso. En caso afirmativo, continúe y envíe su trabajo al Team Server y
configure la historia como Listo.

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.

Según esa historia de usuario, Jimmy quiere poder eliminar eventos de


capacitación, pero solo si nadie se ha registrado para ese evento todavía. De lo
contrario, podría tener algunas caras infelices si los alumnos ya pagaron para
asistir a un determinado evento de capacitación y luego el evento se canceló de
repente. O los alumnos se presentarían al evento, pero, por supuesto, no habría
capacitación porque el evento había sido cancelado.
Por lo tanto, debe asegurarse de que cuando el usuario intente eliminar un objeto,
la aplicación lo impida si hay objetos asociados a él. Esto se puede lograr con una
configuración en el modelo de Dominio, específicamente en las propiedades de
una entidad. El comportamiento que deseas activar en este caso se
llama prevención de eliminación , y es una de las opciones de la siguiente
imagen:

Analicemos un poco esta ventana. La primera sección, multiplicidad , le muestra


de qué tipo es una asociación.
Las siguientes dos opciones le muestran la configuración del comportamiento de
eliminación. En otras palabras, qué debería suceder cuando eliminas uno de los
objetos asociados. En el ejemplo, cuando desea eliminar el objeto 'TrainingEvent',
tiene tres opciones:

• Mantener objeto(s) de 'Registro' . Esto significa que podrás eliminar el evento de


capacitación y todos los registros que pertenecen al mismo permanecerán en el
sistema. Esto también se denomina sin predefinición y es la configuración
predeterminada para el comportamiento de eliminación.
• Elimine también los objetos de 'Registro' . Esto significa que el evento de
capacitación y todos los registros que pertenecen al mismo se eliminarán del
sistema. Este tipo de comportamiento de eliminación se denomina eliminación en
cascada .
• Elimine el objeto 'TrainingEvent' solo si no está asociado con los objetos
'Registration' . Esto significa que el evento de capacitación solo se puede eliminar
si aún no tiene ningún registro conectado. Este tipo de comportamiento de
eliminación se denomina prevención de eliminación . Al seleccionar esto,
también tiene la opción de mostrar un mensaje de error al usuario final,
informándole por qué no puede eliminar un determinado objeto.
Consejo

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.

En las siguientes tareas, le brindará a Jimmy la posibilidad de eliminar un evento


de capacitación. ¡Empecemos!

Agregar botón Eliminar


En primer lugar, asegurémonos de que haya un botón de eliminación en su lugar. Jimmy
quiere poder eliminar eventos de capacitación, por lo que necesitará un botón de eliminación
en la página TrainingEvent_Overview.
Para hacer eso:

1. Abra la página TrainingEvent_Overview en Mendix Studio Pro.


2. En la Caja de herramientas , busque el botón Eliminar .
3. Colóquelo en el elemento de vista de lista, a la derecha del botón > .

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

Agregar comportamiento de eliminación: prevención


de eliminación
¡Genial, el botón está listo! Ahora es el momento de configurar el comportamiento de
eliminación. Jimmy quiere que los eventos de capacitación se eliminen solo cuando todavía no
haya ningún registro conectado a ellos.
1. Usted administra el comportamiento de eliminación en el modelo de dominio , así
que continúe y ábralo.
2. Haga doble clic en la asociación Registration_TrainingEvent para abrir sus
propiedades. Se abrirá la siguiente ventana:

3. En Al eliminar 'TrainingEvent', seleccione Eliminar objeto 'TrainingEvent' solo si


no está asociado con los objetos 'Registro' . Deje las otras opciones como están
configuradas de forma predeterminada.
4. Agregue un mensaje de error en el área de texto que aparece bajo Eliminar objeto
'TrainingEvent' solo si no está asociado con los objetos 'Registro' . Este mensaje
de error se muestra al usuario final cuando se evita la eliminación. Quizás algo como
esto: Lo sentimos, este evento de capacitación no se puede eliminar. ¡La gente ya se
ha registrado!
5. Haga clic en Aceptar .

¿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 .

6. ¡Felicidades! Jimmy ahora puede cancelar eventos de entrenamiento programados. ¡Él


estará muy feliz con eso! Confirme su funcionalidad recién creada en Team Server y
configure la historia en Listo . ¡No olvides seleccionar la historia como historia de
usuario relacionada durante la confirmación!
AnteriorPróximo

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).

Eliminar objetos con eliminación en cascada


Puede crear esta funcionalidad utilizando el mismo enfoque que en la tarea anterior. Estos son
los pasos que deberá seguir:

1. Establezca la siguiente historia de usuario en En ejecución: Como administrador,


quiero poder eliminar alumnos y todos sus registros, para poder eliminarlos del
sistema si ya no desean ser estudiantes de LearnNow.
2. Agregue un botón Eliminar en la página Trainee_Overview . Haga que el botón se
destaque dándole un icono y un color bonitos. Si necesita ayuda con ese paso, puede
consultar la lección '8.4.1 Agregar botón Eliminar'. Si quieres ahorrar algo de tiempo,
también puedes copiar y pegar el botón de eliminar del último ejercicio aquí. ¡Ambos
hacen la misma cosa! Así es como debería verse su botón al final:

3. Agregue el comportamiento de eliminación en la asociación Registration_Trainee en


el modelo de dominio. Si necesita ayuda con ese paso, puede consultar la lección
'8.5.2 Agregar comportamiento de eliminación: Prevención de eliminación'. Tenga en
cuenta que esta vez también debe seleccionar Eliminar objeto(s) de 'Registro'.

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.

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!

En la pestaña Recursos encontrarás el mpk con la solución del módulo 8.

AnteriorPróximo

You might also like