Documento 5 de Gonzalo
Documento 5 de Gonzalo
Learning Objectives
By the end of this module, you will be able to:
• Explain the relation between the Domain Model and the Database
• Create a training events page and add data from the home page
• Identify when to use information entities and extend the domain model
Jimmy is quite pleased with the work you have done. He can start adding his data to the
system, which is really helpful for LearnNow. Let's have a look at how your data is structured
so far! To do this, we will have a look at the Domain Model.
The next feature that would be useful for Jimmy is the capability to schedule training events, as
detailed in his next user story: As an administrator, I want to be able to schedule a training
event at any time, so that the teachers can see their schedule, even from their phone.
With this feature, Jimmy can schedule trainings in the app, and the teachers can see when and
where they have to host a course.
The training events are a new piece of data. For it to be dynamic, it needs to be in the domain
model. Adding new entities or attributes to the domain model is something we call extending
the domain model. This will cause your database to change, but Mendix handles all of that for
you.
The Database
The structure of the domain model determines what the database will look like. Each entity will
become a database table, and each attribute will become a column in the database. Every
object you store in the database (for example, a course) becomes a row in the corresponding
database table. This also means that if something is not in the domain model, you also can't
add that information to the database.
This is what the database table for the Course entity looks like:
You see that ID column? That is not an attribute. So how did it end up in the database table?
This is something Mendix does automatically for you, because every object always needs a
unique identifier (an ID) so that the system knows which object it is. Even if you create two
identical objects with identical attribute values, they will still have two unique ID numbers and
be treated as two different objects.
You can change the domain model as often as you like, and the database will synchronize
when you run the app again. Also, when you change the name of an entity or attribute, your
app will still work immediately, because Mendix Studio Pro will automatically apply these
changes everywhere.
PreviousNext
1. Go to the Developer Portal and set the following story to In Progress: "As an
administrator, I want to be able to schedule a training event at any time, so that the
teachers can see their schedule even from their phone."
Jimmy added the following description to the story: "When scheduling a training event, a
location and course will need to be selected along with which teacher is going to host the
event. This way, the teacher can see which course they will have to teach and where. I should
also be able to select a start and end date for the course, so the teachers can see on which
days the course will occur."
2. Open the domain model and add a new entity called TrainingEvent. Use PascalCase
for the name, and remember that entity names should always be singular!
Jimmy said that he wants a training event to have a start date and an end date.
3. Add two attributes to the TrainingEvent entity: StartDate and EndDate. You can
probably guess which attribute type this entity should have: Date and Time!
Excellent! You have added a new entity to your domain model. Your domain model should now
look like this:
You might be wondering: Why does the TrainingEvent entity only have two attributes?
Shouldn't it include location information too? The answer is that we already have that sort of
information stored in the other entities. We just have to connect TrainingEvent to them using
Associations.
PreviousNext
Associations in the Domain Model
In the Domain Model, Entities can interact with one another via Associations. They look like
arrows between Entities. For instance, you need to be able to store in the system what course
will be given, where it will be hosted, who will teach it, and when it will happen.
The way Jimmy runs things, a training event will always be for only one course, at one location,
and hosted by one teacher. If you think about it from the other direction, all of those things will
be reused for multiple training events. Over time, a course will be scheduled more than once,
locations will be used more than once, and teachers will host many training events.
For each association that you add to your domain model, a new database table will be created.
This table will store the ID's of objects connected to each other. Just like Entities, remember
that an Association is the blueprint. The objects themselves must then be associated to each
other and their IDs stored in the table. Making an association in the domain model does not
mean that all Objects involved will be associated with each other. It just means the possibility
now exists to do so.
In Mendix Studio Pro, you can choose between three types of associations, which we are
going to explain by using football as an example. (American or soccer, your choice!) In football,
you have teams, players, stadiums, and leagues. The possible associations are described
below.
This is the most commonly used association. In the example, this is the association between a
player and a team. One player always plays for one specific team, but a team has multiple
players.
This is the association where two objects can only be associated to each other and not to any
other objects at the same time. In the football example, this is shown in the association
between a team and a stadium. A team can have only one home stadium, and a stadium can
have only one home team. Their mascot is also in a one-to-one association.
Reference Set (* – *)
This is also called a many-to-many association. In the case of the football example, a league is
played by many teams, but a team can also compete in multiple leagues.
Let's take another look at the description Jimmy added to the user story: "When scheduling a
training event, a location and course will need to be selected along with which teacher is
going to host the event."
Before you can start thinking about signing up trainees, you first need to be able to add training
events to your schedule. So, for this user story, you will focus on that functionality, and in the
next user story, you will look into adding registrations to the training events.
PreviousNext
Add Associations
Let's put this into practice! The training event needs to have a connection to a course, location,
and trainer. This way, you can store in the system what course will be given, where it will be
hosted, and who will teach it.
1. Hover your mouse over the TrainingEvent entity. Click on the white circle that appears
on the border of the entity and drag a new association to the Course entity. The
association will be created as a one-to-many association by default. To change the
association type, just double click in the association and select a different type.
Notice associations have names too! The name of this association is TrainingEvent_Course.
This is the naming convention for associations: Entity1_Entity2. You can make the
association name more descriptive if you need to distinguish between two or more similar
associations, but the underscore that shows where one entity ends and the other begins is
important. In simpler apps, the default names are best.
2. Go ahead and create all the associations according to the description that Jimmy
provided. Make sure to rearrange your domain model (if necessary), so that all the
association labels are easy to read.
When finished, you should see this. This part of the app is important because everything else
you do from now on will be based on it, so make sure you have everything right:
Tip: Did you accidentally create the association in the wrong direction? No worries, you can
just delete it and recreate it in the other direction.
PreviousNext
Create Training Event Overview
Now that you've extended the domain model, it's time to create the pages for
managing training events. You will do this by creating an Overview and NewEdit
page as you have done before, but this time you will need to utilize your new
associations to get and set all the needed information. As you can see in the
wireframe below, the Training Event Overview page will need to display data from
four different entities.
Let's start with the homepage:
1. Create a fifth homepage button. Go to your Home_Web page and add a row
to the Layout grid. Duplicate the column layout of the first row by choosing
the 3,3,3,3 option.
2. Drag and drop a Button from the toolbox or copy and paste one that you
already have.
Change the button's caption to Training Events, and look for the calendar icon.
Also set the Appearance settings Size: Large and Full width.
2. Go to the On click field and select show a page. In the select web page
pop up, click New.
3. Time to configure your new page. Set the page name to
TrainingEvent_Overview. Choose Atlas_Default for the Navigation layout
and the List template like the other overview pages. Click OK. Click OK
again on the button edit window.
Looking good! In the next bit, you'll cross those associations to get data from four
different entities on to this page.
• Who is teaching it
• The location
1. Let's prepare the text widgets you will use. Copy and paste the Secondary text widget
two more times:
When this page is finished, you'll want it to show four things: the Course Title, Start and End
dates, Teacher Name and Location name. You can also use some static text to make it more
understandable. Here's what it will look like once all that is configured:
2. Now, you can use an association for the course title.a. Double-click the first List item
title. (This will become {.../Course/Title} as shown in the image above.) b. Click Edit
next to the Caption field in the Edit Text window.c. In the Caption field on the Edit
Caption window, type {1}. Click New to set the parameter that will be displayed in {1}.
Click Select in the Edit Template Parameter pop up, expand the Course dropdown,
and pick Title. (See the screenshot below to compare to the popups you have open.) d.
Click Select and then OK on each open window. You've just used an association! Let's
go grab the rest.
3. Continue with the two Dates, then the Teacher Name, then the Location Address.
4. Cool! The Training Event Overview is complete. Add a Navigation menu item that goes
to this page so that you can get to it from anywhere within the app.
The final step is to create the New button and the NewEdit page for Training Events.
PreviousNext
Create Training Event NewEdit Page
Now you have to create the New button and the NewEdit page that will let you configure
Training Events. You will create these in the same way you did the previous four, but the
NewEdit page will turn out a bit differently because it will use Associations rather than just text
entry fields.
1. In the header of the Training Event overview page, create a new column and set it to
Auto-fit content.
2. Drag and drop a Create button from the toolbox into the new column.
3. In the pop up window, select TrainingEvent entity.
7. Go check out your new TrainingEvent_NewEdit page. See those bottom three widgets?
Those use the associations you set up. Move the two Date widgets beneath the Course
widget just so this form makes a bit more sense.
Those three association input widgets are called Reference selectors, and they are not
connected to attributes. (Sometimes they are interchangeably referred to as Drop-Downs, but if
you look in the Toolbox you will see that these are two different widgets. What we're using here
is a Reference selector, not a true Drop-down.) Reference selectors allow you to set
associations between existing objects — in this case, between this new Training Event and a
Course, a Location, and a Teacher which are already in the database.
Mendix has automatically set these widgets up for you, but in the properties of a reference
selector you can choose which attribute of the target entity to display in the list. In our case,
Titles and Names work just fine but you may have to configure these yourself in the future.
Here is what your page should look like:
8. Lastly, configure the On-click behavior of the List view on the TrainingEvent_Overview
page to go to the TrainingEvent_NewEdit page for editing existing objects.
9. Run your app and try it out! Schedule some training events. Now you will be able to
select all the necessary information!
10. When you are done, go to the Developer Portal and set this user story to Done.
11. Commit your work, since you've completed a feature. Mission accomplished!
PreviousNext
Add Training Events from the Homepage
Jimmy is very pleased with the new functionality since it helps him in his daily job. However, he
finds that 90% of his work revolves around scheduling training events. By contrast, he rarely
hires new teachers or finds new locations. With this in mind, he asks if he could have a button
on the homepage to schedule a training event directly. This button will go straight to the
Training Event NewEdit page rather than an overview page.
So together with Jimmy you have written the following user story:
As an administrator, I want to be able to schedule a training event directly from the homepage,
so I spend as little time as possible on this. Before starting with the new button, find the user
story in the Developer Portal and set it to In Progress.
1. Go to the Home_Web page. Add a new button to the homepage next to the Training
Events one. This time, copy and paste a button you already have to speed up the
process, and then adjust its settings.
2. Make sure the new button has this configuration:
Test it out, and if you're sure everything works, complete this user story.
Nice job! With the new button you just created, Jimmy can now schedule new training events
directly from the homepage of his app. Next up you'll tackle the last bit of information to get
Jimmy's company back in business: signing up trainees.
PreviousNext
Information Entities
Just a bit ago, you built the functionality to schedule training events and you learned about the
Domain model and associations. You created connections between TrainingEvent, Course,
Location and Teacher. Did you notice that Trainee is not connected to another entity yet? The
next user story will change that: As an administrator, I want to be able to add registrations to a
training event, so that my teachers know who their students will be.
Jimmy wants to be able to register Trainees to Training Events. This means that they will
need to be connected by an association. A training event can have multiple Trainees in
attendance, and a Trainee can attend multiple training events. So, this looks like it will be a
many-to-many association, also known as a reference set. However, Jimmy would like to be
able to add some information to this association. Specifically, he is requesting to store the date
the trainee signed up, whether or not they came to class, and a unique registration number to
keep better track of the many registrations he'll be dealing with. But you can't store anything in
the association, apart from the connection itself and its name. It also makes no sense to store
this data on either the TrainingEvent or the Trainee, since both need to be able to have
multiple sets of registration info associated with them.
What you need is a different approach than just a regular many-to-many association. You need
an entity in between Trainee and TrainingEvent that says something about the connection
between the two and simplifies it. This is called an information entity.
See how it stores all the requested info? Every time a Trainee signs up for a Training Event,
exactly one Registration will be created. It will be associated with only the Trainee who
registered, and only with the Training Event they registered for. Thus, you can use two one-to-
many associations here instead of a problematic many-to-many. Let's go do this.
PreviousNext
1. Go to the Developer Portal and set the following user story to In Progress: "As an
administrator, I want to be able to add registrations to a training event, so that my
teachers know who their students will be."
2. In the Domain model, place a new entity between TrainingEvent and Trainee and
name it Registration.
3. Give your new entity the requested attributes:
• Number
• This is going to be an AutoNumber attribute because it will auto-increment with
each newly created Registration, which means each Registration will have a
unique registration number.
• Date
PreviousNext
Nested Data
Now of course you'll need an Overview and NewEdit page to manage
Registrations. However, there are some special considerations to take into account
this time around.
If you create an Overview page like you have done in the past with a List view
showing every Registration in the database, it will quickly become too large to be
useful! Jimmy might have ten locations that he trains at, but certainly not a
thousand, so showing them all on one page is fine. But if each Training Event has
the possibility to have ten or more registrations, you can see how we could quickly
wind up with thousands of Registration objects after a few months or years. A
single list of all of them will be impossible to work with.
It needs to be filtered to show only the relevant objects from this large dataset. You
can do this in Mendix with search fields or filters in the data widget, but in this case
we can automate the process even further with something called Nesting. You'll
use nesting to allow Jimmy to look at small lists of Registrations based on which
Training Event he's currently interested in - ten or twenty at a time rather than
hundreds.
Nesting works by placing a List view inside a Data view and configuring both of
them to work together properly. If you want to look at the Registrations of a
particular TrainingEvent, you need to nest a Registration List view inside a
TrainingEvent Data view. This way, Mendix Studio can use the context of the data
view (a particular training event), to only show those registrations that belong to
this training event.
In the next assignment, you'll tackle all that step-by-step. Get ready! This one is
tougher than before!
3. The Select web page window will open. The Registrations page doesn't
exist yet, so click New to create it now.
In the next lecture you will edit the Registration overview page so that it becomes
functional. You will learn how to nest data using Training Events as context.
Data views
The data view widget allows you to look at and change the information of one specific object. In
fact, all the NewEdit pages you have created so far contain data views, because each is editing
one specific object. The data view connects to the context of the page, or the starting point. In
this case, that is the TrainingEvent object. To get to this page, Jimmy will see a list of Training
Events on the Training Event overview page and each one will have a Registrations button
next to it. Depending on which Registrations button he clicks, he can choose which
TrainingEvent object is sent to this new page as the context.
1. Drop a new Data view widget inside the column (which you can find in the Toolbox).
2. Connect Data view widget to the TrainingEvent entity. Do not automatically fill the
contents of the page.
3. Double-click Data view widget. In the Show footer field, click No.
4. Now let's add a header (page title) to the page so that the end-user knows which
training event's registrations they are looking at. At the top of the Toolbox, switch the
toggle from Widgets to Building blocks. Look for the Pageheader with controls
building block in the Toolbox and place it inside the DATA VIEW CONTENT portion of
the data view.
Building blocks have been designed by the Mendix UX Team, so they ensure that you are
adding a user-friendly section to your page. Each one is a template composed of multiple
widgets with styling properties applied. All you have to do is drag and drop the building blocks
into your page and then (if needed) connect them to your data or pages. You can always
change a building block to your preferences once you've placed it.
5. Using the large text widget that comes with it, configure a descriptive title using
information from the Training Event: something like Registrations for the {Course/Title}
on {StartDate}.
6. Delete the white Action button; you won't be needing it, but you'll use the blue one
later.
7. Add a new full-width row to the building block's layout grid. There are a few different
ways to do this.
8. Place a new List view inside the new column that appears.
9. Open the properties of the List view and open the Select Entity window on the Data
source tab. You should see two different Registration options to choose from:
The lower one is the contextual option you're familiar with. If you were to select that one, you
would be shown the unfiltered list of all Registrations in the database. What Jimmy wants is the
top option, underneath the Registration_TrainingEvent dropdown. This will only show
Registrations with an association to the training event the Data view is connected to. Pick the
top Registration and click Select.
Woo, you have just nested data! Now let's use our nested connection to the database to
display some dynamic data.
6. Add a Text widget to your List view content and configure its caption and parameters to
show the Trainee's Name, Registration Number, and Registration Date.
The Registration overview is complete. What is left? A way for Jimmy to add registrations of
course! Next you'll create the NewEdit page. You're in the home stretch for this user story.
PreviousNext
4. Select the On click page and create a new page within the window that pops
up. You know the drill. Registration_NewEdit, Popup layout and Form
Vertical.
2. Open the properties of the list view and change the On click action to Show
a page. Choose your new page, Registration_NewEdit.
3. Open the Registration_NewEdit page you just created. Make sure that the
first thing Jimmy can do on that page is to select a Trainee. Also, this is
probably the most important information about the Registration, so it should
be the first editable field. Move the Trainee selection widget above the Date
selection widget.
4. Run your app locally and try making some registrations. You did it! This user
story is finished. Go to the Developer Portal and set the story to Done.
Summary
In this module, you were introduced to associations, which allows connecting different types of
data together to form relationships.
You've just about got all your UI set up for this app! Jimmy can now do everything he was
doing before manually. But you worked so fast, you've actually got plenty of time left on the
project, so now you can move into some quality of life user stories that will make Jimmy's job
even easier.
PreviousNext
SPANISH
Objetivos de aprendizaje
Al final de este módulo, podrá:
Jimmy está muy satisfecho con el trabajo que has realizado. Puede comenzar a agregar sus
datos al sistema, lo cual es realmente útil para LearnNow. ¡Echemos un vistazo a cómo están
estructurados sus datos hasta ahora! Para ello, echaremos un vistazo al modelo de dominio.
La siguiente característica que sería útil para Jimmy es la capacidad de programar eventos de
capacitación, como se detalla en su siguiente historia de usuario: Como administrador,
quiero poder programar un evento de capacitación en cualquier momento, para que los
profesores puedan ver sus horario, incluso desde su teléfono. Con esta función, Jimmy
puede programar capacitaciones en la aplicación y los profesores pueden ver cuándo y dónde
deben organizar un curso.
Los eventos formativos son un dato nuevo. Para que sea dinámico, debe estar en el modelo
de dominio. Agregar nuevas entidades o atributos al modelo de dominio es algo que llamamos
extender el modelo de dominio. Esto hará que su base de datos cambie, pero Mendix se
encarga de todo eso por usted.
La base de datos
La estructura del modelo de dominio determina cómo se verá la base de datos. Cada entidad
se convertirá en una tabla de base de datos y cada atributo se convertirá en una columna de
la base de datos. Cada objeto que almacena en la base de datos (por ejemplo, un curso) se
convierte en una fila en la tabla de la base de datos correspondiente. Esto también significa
que si algo no está en el modelo de dominio, tampoco podrá agregar esa información a la
base de datos.
Puede cambiar el modelo de dominio tantas veces como desee y la base de datos se
sincronizará cuando vuelva a ejecutar la aplicación. Además, cuando cambias el nombre de
una entidad o atributo, tu aplicación seguirá funcionando inmediatamente, porque Mendix
Studio Pro aplicará automáticamente estos cambios en todas partes.
AnteriorPróximo
Jimmy dijo que quiere que un evento de capacitación tenga una fecha de inicio y una fecha de
finalización.
AnteriorPróximo
Asociaciones en el modelo de dominio
En el modelo de dominio, las entidades pueden interactuar entre sí a través
de asociaciones . Parecen flechas entre Entidades. Por ejemplo, es necesario poder
almacenar en el sistema qué curso se impartirá, dónde se alojará, quién lo impartirá y cuándo
se realizará.
De la forma en que Jimmy dirige las cosas, un evento de capacitación siempre será para un
solo curso, en un lugar y organizado por un solo maestro. Si lo piensas desde el otro lado,
todas esas cosas se reutilizarán para múltiples eventos de capacitación. Con el tiempo, un
curso se programará más de una vez, las ubicaciones se utilizarán más de una vez y los
profesores organizarán muchos eventos de capacitación.
Para cada asociación que agregue a su modelo de dominio, se creará una nueva tabla de
base de datos. Esta tabla almacenará las ID de los objetos conectados entre sí. Al igual que
las Entidades, recuerde que una Asociación es el modelo. Luego, los propios objetos deben
asociarse entre sí y sus ID deben almacenarse en la tabla. Realizar una asociación en el
modelo de dominio no significa que todos los Objetos involucrados estarán asociados entre
sí. Simplemente significa que ahora existe la posibilidad de hacerlo.
En Mendix Studio Pro podrás elegir entre tres tipos de asociaciones, que vamos a explicar
poniendo como ejemplo el fútbol. (¡Americano o fútbol, tú eliges!) En el fútbol, tienes equipos,
jugadores, estadios y ligas. Las posibles asociaciones se describen a continuación.
Esta es la asociación donde dos objetos sólo pueden asociarse entre sí y no con ningún otro
objeto al mismo tiempo. En el ejemplo del fútbol, esto se muestra en la asociación entre un
equipo y un estadio. Un equipo sólo puede tener un estadio local y un estadio sólo puede
tener un equipo local. Su mascota también está en una asociación uno a uno.
Conjunto de referencia (* – *)
A esto también se le llama asociación de muchos a muchos. En el caso del ejemplo del fútbol,
muchos equipos juegan en una liga, pero un equipo también puede competir en varias ligas.
Echemos otro vistazo a la descripción que Jimmy agregó a la historia del usuario: "Al
programar un evento de capacitación, será necesario seleccionar una ubicación y un curso
junto con qué maestro será el anfitrión del evento".
Antes de que pueda empezar a pensar en inscribir aprendices, primero debe poder agregar
eventos de capacitación a su agenda. Entonces, para esta historia de usuario, se concentrará
en esa funcionalidad y, en la siguiente historia de usuario, buscará agregar registros a los
eventos de capacitación.
AnteriorPróximo
Agregar asociaciones
¡Pongamos esto en práctica! El evento de capacitación debe tener una conexión con un curso,
ubicación y capacitador. De esta manera, puedes almacenar en el sistema qué curso se
impartirá, dónde se alojará y quién lo impartirá.
1. Pase el mouse sobre la entidad TrainingEvent. Haga clic en el círculo blanco que
aparece en el borde de la entidad y arrastre una nueva asociación a la entidad
Curso. La asociación se creará como una asociación de uno a muchos de forma
predeterminada. Para cambiar el tipo de asociación, simplemente haga doble clic en la
asociación y seleccione un tipo diferente.
¡Observa que las asociaciones también tienen nombres! El nombre de esta asociación
es TrainingEvent_Course . Esta es la convención de nomenclatura para las
asociaciones: Entity1_Entity2 . Puede hacer que el nombre de la asociación sea más
descriptivo si necesita distinguir entre dos o más asociaciones similares, pero el guión bajo
que muestra dónde termina una entidad y comienza la otra es importante. En aplicaciones
más simples, los nombres predeterminados son los mejores.
2. Continúe y cree todas las asociaciones de acuerdo con la descripción que proporcionó
Jimmy. Asegúrese de reorganizar su modelo de dominio (si es necesario) para que
todas las etiquetas de asociación sean fáciles de leer.
Cuando termine, debería ver esto. Esta parte de la aplicación es importante porque todo lo
que hagas a partir de ahora se basará en ella, así que asegúrate de tener todo bien:
AnteriorPróximo
Crear descripción general del evento de capacitación
Ahora que ha ampliado el modelo de dominio, es hora de crear las páginas para gestionar
eventos de formación. Lo hará creando una página Descripción general y Nueva edición como
lo hizo antes, pero esta vez necesitará utilizar sus nuevas asociaciones para obtener y
configurar toda la información necesaria. Como puede ver en la estructura alámbrica a
continuación, la página Descripción general del evento de capacitación deberá mostrar datos
de cuatro entidades diferentes.
1. Crea un quinto botón de página de inicio. Vaya a su página Home_Web y agregue una
fila a la cuadrícula de Diseño. Duplique el diseño de columnas de la primera fila
eligiendo la opción 3,3,3,3.
2. Arrastre y suelte un botón desde la caja de herramientas o copie y pegue uno que ya
tenga.
¡Luciendo bien! En el siguiente paso, cruzará esas asociaciones para obtener datos de cuatro
entidades diferentes en esta página.
AnteriorPróximo
Usar asociaciones en parámetros
Ahora que ha creado la página Descripción general, debe configurar la vista de lista para
mostrar a los estudiantes la siguiente información:
• en que fechas
• La locación
1. Preparemos los widgets de texto que utilizará. Copie y pegue el widget de texto
secundario dos veces más:
Cuando finalice esta página, querrá que muestre cuatro cosas: el título del curso, las fechas
de inicio y finalización, el nombre del profesor y el nombre de la ubicación. También puedes
utilizar texto estático para hacerlo más comprensible. Así es como se verá una vez que todo
esté configurado:
3. Continúe con las dos fechas, luego el nombre del maestro y luego la dirección de la
ubicación.
El último paso es crear el botón Nuevo y la página NuevoEditar para Eventos de capacitación.
AnteriorPróximo
Crear evento de capacitación Nueva página de
edición
Ahora tienes que crear el botón Nuevo y la página NuevoEditar que te permitirá configurar
Eventos de capacitación. Los creará de la misma manera que los cuatro anteriores, pero la
página NewEdit resultará un poco diferente porque usará Asociaciones en lugar de solo
campos de entrada de texto.
Mendix ha configurado automáticamente estos widgets para usted, pero en las propiedades de
un selector de referencia puede elegir qué atributo de la entidad de destino mostrar en la
lista. En nuestro caso, los Títulos y Nombres funcionan bien, pero es posible que tengas que
configurarlos tú mismo en el futuro. Así es como debería verse su página:
11. Confirma tu trabajo, ya que has completado una función. ¡Misión cumplida!
AnteriorPróximo
Agregar eventos de capacitación desde la página de
inicio
Jimmy está muy satisfecho con la nueva funcionalidad, ya que le ayuda en su trabajo
diario. Sin embargo, descubre que el 90% de su trabajo gira en torno a la programación de
eventos de formación. Por el contrario, rara vez contrata nuevos profesores o encuentra
nuevos lugares. Teniendo esto en cuenta, pregunta si podría tener un botón en la página de
inicio para programar un evento de capacitación directamente. Este botón irá directamente a la
página NewEdit del evento de capacitación en lugar de a una página de descripción general.
Así que, junto con Jimmy, has escrito la siguiente historia de usuario:
Como administrador, quiero poder programar un evento de formación directamente desde la
página de inicio, así que dedico el menor tiempo posible a esto. Antes de comenzar con el
botón nuevo, busque la historia del usuario en el Portal del desarrollador y configúrela en En
progreso .
Pruébelo y, si está seguro de que todo funciona, complete esta historia de usuario.
¡Buen trabajo! Con el nuevo botón que acaba de crear, Jimmy ahora puede programar nuevos
eventos de capacitación directamente desde la página de inicio de su aplicación. A
continuación, abordará la última información para que la empresa de Jimmy vuelva a
funcionar: inscribir aprendices.
AnteriorPróximo
Entidades de Información
Hace un momento, creó la funcionalidad para programar eventos de capacitación y aprendió
sobre el modelo de dominio y las asociaciones. Creó conexiones entre TrainingEvent, Course,
Location y Teacher. ¿Notaste que Trainee aún no está conectado a otra entidad? La siguiente
historia de usuario cambiará eso: como administrador, quiero poder agregar inscripciones a un
evento de capacitación, para que mis profesores sepan quiénes serán sus estudiantes.
Jimmy quiere poder registrar aprendices en eventos de capacitación . Esto significa que
deberán estar conectados por una asociación. Un evento de capacitación puede tener la
asistencia de varios alumnos y un alumno puede asistir a varios eventos de
capacitación. Entonces, parece que será una asociación de muchos a muchos, también
conocida como conjunto de referencia. Sin embargo, a Jimmy le gustaría poder agregar
alguna información a esta asociación. Específicamente, solicita almacenar la fecha en que se
inscribió el alumno, si asistió o no a clase, y un número de registro único para realizar un
mejor seguimiento de los muchos registros con los que tendrá que lidiar. Pero no puedes
almacenar nada en la asociación, aparte de la conexión misma y su nombre. Tampoco tiene
sentido almacenar estos datos en TrainingEvent o Trainee, ya que ambos deben poder tener
múltiples conjuntos de información de registro asociados.
AnteriorPróximo
• Número
• Este será un atributo de Autonumérico porque se incrementará
automáticamente con cada Registro recién creado , lo que significa
que cada Registro tendrá un número de registro único.
• Fecha
• Por supuesto, esto será un atributo DateAndTime, pero ¿no sería
bueno si la fecha se estableciera automáticamente en el momento en
que se creó el registro? Puede hacerlo estableciendo un valor
predeterminado. A medida que crea el atributo, establezca el valor
predeterminado en la parte inferior en [%CurrentDateTime%] .
• Asistió
• Esto dirá si alguien apareció o no, por lo que será un atributo
booleano. Sí o no.
Datos anidados
Ahora, por supuesto, necesitará una página Descripción general y Nueva edición para
administrar los registros. Sin embargo, hay algunas consideraciones especiales a tener en
cuenta esta vez.
Si crea una página de descripción general como lo hizo en el pasado con una vista de lista
que muestra todos los registros en la base de datos, rápidamente se volverá demasiado
grande para ser útil. Jimmy puede tener diez ubicaciones en las que entrena, pero ciertamente
no mil, por lo que mostrarlas todas en una página está bien. Pero si cada Evento de
Capacitación tiene la posibilidad de tener diez o más registros, puede ver cómo rápidamente
podríamos terminar con miles de objetos de Registro después de unos meses o años. Será
imposible trabajar con una lista única de todos ellos.
Es necesario filtrarlo para mostrar solo los objetos relevantes de este gran conjunto de
datos. Puedes hacer esto en Mendix con campos de búsqueda o filtros en el widget de datos,
pero en este caso podemos automatizar aún más el proceso con algo
llamado Nesting . Utilizará el anidamiento para permitirle a Jimmy ver pequeñas listas de
registros según el evento de capacitación que le interese actualmente: diez o veinte a la vez
en lugar de cientos.
El anidamiento funciona colocando una vista de lista dentro de una vista de datos y
configurándolas para que funcionen juntas correctamente. Si desea ver los registros de
un TrainingEvent en particular , debe anidar una vista de lista de registros dentro de una
vista de datos de TrainingEvent . De esta manera, Mendix Studio puede utilizar el contexto
de la vista de datos (un evento de capacitación en particular), para mostrar solo aquellos
registros que pertenecen a ese evento de capacitación.
• Cree una nueva página para la descripción general del registro y vincule el botón que
acaba de crear a esa página.
• Coloque una Vista de lista dentro de una Vista de datos , de modo que solo se
muestren las inscripciones para ese evento de capacitación específico.
• Configure datos dinámicos dentro de la vista Datos para mostrar información del
evento de capacitación.
• Configure datos dinámicos dentro de la vista de lista para mostrar una lista de
información de registro.
• Cree un nuevo botón y una página de detalles para permitir al usuario crear un nuevo
registro para ese evento de capacitación específico.
En la próxima tarea, abordarás todo eso paso a paso. ¡Prepararse! ¡Éste es más duro que
antes!
AnteriorPróximo
Crear una página de registro
Tiene el marco implementado para almacenar información de registro. Ahora sólo necesita
una interfaz de usuario para poder ingresar a la aplicación. ¡Vamos!
3. Se abrirá la ventana Seleccionar página web . La página Registros aún no existe, así
que haga clic en Nuevo para crearla ahora.
• Vas a crear esta página desde cero, así que selecciona la plantilla en blanco .
6. ¿Listo para un atajo de Studio Pro? Haga clic con el botón derecho en el botón
Registros terminados y haga clic en Ir a la página en la que haga clic
(MyFirstModule.TrainingEvent_Registration_Overview) . Hay muchos lugares en
Studio Pro con atajos como este. ¡Experimento!
En la próxima conferencia editará la página de descripción general de registro para que sea
funcional. Aprenderá cómo anidar datos utilizando Eventos de capacitación como contexto.
AnteriorPróximo
Cómo anidar datos
Ahora debería estar en la página TrainingEvent_Registration_Overview que acaba de
crear. La página solo tiene una columna vacía, por lo que lo primero que debe hacer es
agregar una vista de datos dentro de esa columna.
Vistas de datos
Los bloques de construcción han sido diseñados por el equipo de UX de Mendix, por lo que
garantizan que agregue una sección fácil de usar a su página. Cada uno es una plantilla
compuesta por múltiples widgets con propiedades de estilo aplicadas. Todo lo que tienes que
hacer es arrastrar y soltar los bloques de construcción en tu página y luego (si es necesario)
conectarlos a tus datos o páginas. Siempre puedes cambiar un bloque de construcción según
tus preferencias una vez que lo hayas colocado.
5. Usando el widget de texto grande que viene con él, configure un título descriptivo
usando información del evento de capacitación: algo así como Registros para el
{Curso/Título} el {StartDate} .
6. Elimine el botón de acción blanco ; No lo necesitarás, pero usarás el azul más tarde.
7. Agregue una nueva fila de ancho completo a la cuadrícula de diseño del bloque de
construcción. Hay algunas formas diferentes de hacer esto.
8. Coloque una nueva vista de Lista dentro de la nueva columna que aparece.
9. Abra las propiedades de la vista de lista y abra la ventana Seleccionar entidad en la
pestaña Fuente de datos. Deberías ver dos opciones de registro diferentes para elegir:
¡Vaya, acabas de anidar datos! Ahora usemos nuestra conexión anidada a la base de datos
para mostrar algunos datos dinámicos.
La descripción general del registro está completa. ¿Lo que queda? ¡Una forma para que
Jimmy agregue registros, por supuesto! A continuación creará la página NewEdit. Estás en la
recta final de esta historia de usuario.
AnteriorPróximo
Resumen
En este módulo, conoció las asociaciones, que permiten conectar diferentes tipos
de datos para formar relaciones.
¡Ya casi tienes toda tu interfaz de usuario configurada para esta aplicación! Jimmy
ahora puede hacer todo lo que hacía antes manualmente. Pero trabajó tan rápido
que en realidad le queda mucho tiempo en el proyecto, por lo que ahora puede
pasar a algunas historias de usuarios de calidad de vida que harán que el trabajo
de Jimmy sea aún más fácil.