Note: You are currently viewing documentation for Moodle 2.4. Up-to-date documentation for the latest stable version of Moodle may be available here: Configurable reports.

Configurable reports: Difference between revisions

From MoodleDocs
(New page: == Instalación == # Descargar el fichero de instalación del bloque "Custom Report" y descomprimirlo en el directorio '''/blocks''' del directorio de instalación de Moodle. # Iniciar se...)
 
No edit summary
Line 1: Line 1:
== Instalación ==
== Installation ==


# Descargar el fichero de instalación del bloque "Custom Report" y descomprimirlo en el directorio '''/blocks''' del directorio de instalación de Moodle.
# Download the Custom Reports installation file and unzip it to the '''\blocks''' directory in your Moodle folder.
# Iniciar sesión como administrador y pulsar en el enlace Notificaciones, dentro del bloque de administración del sitio.
# Login to Moodle as Administrator and click Notifications under Site Administration.


Para más información véase [https://docs.moodle.org/en/Installing_contributed_modules_or_plugins Installing contributed modules or plugins] (en inglés)


== Resumen ==
For more information see [[Installing contributed modules or plugins]]


Este bloque sirve para generar informes a medida de Moodle.
== Overview ==


Ha sido diseñado de forma modular para permitir a los desarrolladores crear nuevos plugins en menos de una hora.
This block is a Moodle custom reports builder.


=== ¿Quién puede crear informes a medida? ===
It is designed in a modular way to allow developers to create new plugins in less than an hour.


Cualquier usuario que tenga los permisos '''block/custom_reports:managereports'', '''blocks/custom_reports:manageownreports''' o '''block/custom_report/managesqlreports''' asignados en un CURSO o en el SITIO (estos permisos se definen durante la instalación del bloque).


=== ¿Qué tipo de informes puedo crear? ===
'''Who can create custom reports?'''


* Informes de cursos, con informaciones relativas a los cursos.
Anyone with block, managereports or manageownreports permissions at SITE level or COURSE level.
* Informes de usarios, con informaciones relativas a los usuarios y su actividad en un curso.
* Informes SQL personalizados, consultas SQL personalizadas. Este bloque puede usar las mismas consultas SQL que el plugin  [http://moodle.org/mod/data/view.php?d=13&rid=2884 de consultas SQL personalizadas de Tim Hunt].


Nota para los desarrolladores: se pueden crear sus propios tipos de informes.


=== ¿Quién puede ver los informes? ===
'''What type of reports can I create?'''


Cuando se crea un informe se puede elegir qué usuarios pueden verlo.
- Courses reports, with information regarding courses.


Los informes se muestra en un bloque del curso o en la portada del sitio.
- Users reports, with information regarding users and their activity in a course.


== Cómo crear un informe ==
- Custom SQL Reports, custom SQL queries. This block can use the same SQL queries that [http://moodle.org/mod/data/view.php?d=13&rid=2884 Tim Hunt's Custom SQL queries] plugin.


Este es un proceso muy sencillo. Si va a crear un informe para un curso, necesita añadir el bloque en el curso y pulsar sobre "Gestionar informes". Por su parte, para los informes del sitio, añada el bloque en la portada y pulse sobre el enlace "Gestionar informes".
Note for developers: You can create your own type of reports.


Necesita introducir un nombre, una descripción (opcional) y tiene que elegir el tipo de informe, paginación y formatos de exportación.


Dependiendo del tipo de informe elegido habrá más o menos pestañas. Estas son las pestañas para los informes de cursos y usuarios:
'''Who can view the reports?'''


* '''Columnas''': Aquí se puede elegir las diferentes columnas del informe, dependiendo del tipo de informe (Nombre del curso, Nombre de pila del usuarios, etc.)
When you create a report you can select which users can view it.
* '''Condiciones''': Aquí se pueden definir las condiciones (p.ej., sólo cursos de esta categoría, sólo usuarios de España, etc.)
 
* '''Ordenación''': Aquí se puede elegir como ordenar el informe usando los campos y direcciones (ascendente, descendente).
The reports are displayed in a block in the course or site frontpage.
* '''Filtros''': Aquí se puede elegir qué filtros se visualizarán.
 
* '''Plantilla''': Se puede modificar la disposición del informe creando una plantilla.
== Creating a report ==
* '''Permisos''': Aquí se puede escoger quien puede ver el informe.
 
* '''Cálculos''': Aquí se pueden añadir cálculos para las columnas; p.ej., media del número de usuarios matriculados en los cursos.
 
* '''Gráficas''': Aquí se pueden añadir gráficas al informe basadas en las columnas del informe y los valores.
This is a very simple process. 
* '''Ver informes''': Auto explicativa
 
If you are going to create a report for a course, you have to add the block in the course and click in the "Manage reports" link.
 
On the other hand, for site reports, add the block in the frontpage and click in the "Manage reports" link.
 
You must enter a name, an optional description, and you have to choose the type of report, pagination and exports formats.
 
Depending on the report choosen, there will be more or less tabs. These are the tabs for the courses and users report:
 
'''Columns''': Here you can choose the differents columns of your report depending on the type of report. (Course Name, User firstname, etc..)
 
'''Conditions''': Here you can define the conditions (i.e, only courses from this category, only users from Spain, etc.)
 
'''Ordering''': Here you can choose how to order the report using fields and directions.
 
'''Filters''': Here you can choose which filters will be displayed.
 
'''Template''': You can modify the report's layout by creating a template.
 
'''Permissions''': Here you can choose who can view a report.
 
'''Calculations''': Here you can add calculations for columns, i.e: average of number of users enrolled in courses
 
'''Plots''': Here you can add graphs to your report based on the report columns and values.
 
'''View report''': Self explanatory


== Tutorial ==
== Tutorial ==


=== Como crear un informe de usuario ===
=== Creating a users' report ===
 
Requirements: ''Users from Spain, but no from Madrid, in this course. This report can be viewed only by users from Spain. A filter based on the user's city must be displayed. A pie plot showing the users' cities is required. A calculation table showing the total forum post views is required. The report must be order by users' lastname.''
 
 
Let's see how easy it is!
 
First of all, install the block.
 
Go to the course where the report will be created.
 
Add an instance of the Custom Reports block.
 
Click on "Manage reports"
 
Click on "Add report"


Requisitos: ''Usuarios de España, pero no de Madrid, en este curso. Este informe se puede ver sólo por usuarios de España. Hay que visualizar un filtro basado en la ciudad del usuario. Se pide mostrar una gráfica de tarta con las ciudades de los usuarios. Se pide una tabla calculada que muestre el total de vistas de mensajes de foros El informe debe ordenarse por el apellido de los usuarios''.
Enter a name, a description and choose "Users report" as Type of Report


¡Veamos qué fácil es!
The report will be saved and you will be redirected to the first Tab named "Columns".


# Primero de todo, instale el bloque.
# Vaya al curso donde se quiere crear el informe.
# Añada una instancia del bloque "Informes personalizados".
# Pulse en "Gestionar informes".
# Pulse en "Añadir informe".
# Introduzca un nombre, una descripción y elija "Informes de usuarios" como tipo de informe.
# Opcionalmente puede marcar las casillas "Exportar en formato ODS" y "Exportar en formato XLS" si desea poder exportar el informe en alguno de estos formatos.
# Pulse el botón "Agregar".
# Se guardará el informe y se le redirigirá a la pestaña denominada "Columnas".


==== Añadir columnas ====
'''Adding Columns'''


Aquí se puede efinir las propiedades de la tabla del informe como anchura, alineación, relleno de las celdas, espaciados de las celdas, etc.
Here you can define the report table properties, width, align, cell padding, cell spacing, etc..
Add a Column called "User profile field"
 
Choose the field "firstname" and enter a name for the column in the text field. You can leave blank the rest of elements.
 
Repit the process above for the lastname and city fields.
 
Add a Column called "User module actions".
 
Choose a module from the list, in this example, a forum.


# Añada una columna de tipo "Campo del perfiel de usuario"
# Teclee un nombre para esta columna y en el desplegable llamado "Columna" elija el valor "firstname". Puede dejar en blanco el resto de elementos. Pulse sobre el botón "Agregar".
# Repita el proces para los campos "lastname" y "city".
# Añada una nueva columna de tipo "Acciones de usuario en el módulo".
# Teclee un nombre parae esta columna y elija un módulo de la lista, en nuestro caso, el foro sobre el que queremos elaborar el informe. Pulse sobre el botón "Agregar".
   
   
==== Añadir condiciones ====
'''Adding Conditions'''


# Pulse en la pestaña "Condiciones".
Click on the Conditions Tab.
# Añada una condición del tipo "Condición sobre campo de perfil del usuario".
# Escoga la columna "country" de la lista desplegable, el operador "=" e introduzca el valor "ES" (este es el código internacional para España tal y como lo almancena Moodle internamente). Pulse el botón "Agregar".
# Añada una nueva condición del tipo "Condición sobre campo de perfil del usuario".
# Escoja la columna "city", el operador "<>" e introduzca el valor "Madrid". Pulse el botón "Agregar".
# Añada una condición del tipo "Usuarios en el curso donde se ha creado el informe" y escoja el valor "Student". Pulse el botón "Agregar".


Estas son las condiciones principales del informe. Note que en la parte inferior hay una caja de texto llamada "Condición lógica" con el texto:
Add a Condition named "User field Condition".


  c2 and c1 and c3
Choose the column "Country", the Operator "=", and enter the value "ES" (this is the international code for Spain as Moodle stores it).


Aquí se puede definir una condición lógica cualquiera. En este caso no necesitamos editar esta condición, pero puede crear expresiones complejas como:
Add a Condition named "User field Condition".


  (c1 and c2) or (c4 and c3)
Choose the column "city", the Operator "<>", and enter the value "Madrid".


==== Añadir ordenación ====
Add a Condition named "Users in current report course".


# Pulse en la pestaña "Ordenación".
These are the main conditions of the reports. Note that at the bottom there is a text box called condition, with this text:
# Añada una ordenación del tipo "Ordenación por campo de usuario".
# Escoja la columna "lastname" y la ordenación "ASC" (ascendente). Pulse "Agregar".


==== Añadir filtros ====
"c2 and c1 and c3"


# Pulse en la pestaña "Filtros".
Here you can define a logic condition, in this case, we don't need to edit this condition but you can create complex expressions like:
# Añáda un filtro del tipo "Filtro sobre campo del perfil del usuario".
# Escoja el campo "city". Pulse "Agregar".


==== Añadir permisos ====
(c1 and c2) or (c4 and c3)


# Pulse en la pestaña "Permisos".
# Añada un permiso del tipo "Valor en el perfil del usuario".
# Escoja la columna "country" e introduzca el valor "ES". Pulse el botón "Agregar".


Aquí puede añadir más tipos de permisos y la condición lógica que debe cumplirse en caso de tener más un tipo de permiso.
'''Adding Ordering'''


==== Añadir cálculos ====
Click on the Ordering Tab.


# Pulse en la pestaña "Cálculos".
Add a ordering named "User field ordering".
# Añada un cálculo de tipo "Suma".
# Escoja la columna que representa la acción del usuario en el módulo (en nuestro caso el foro).


==== Añadir gráficas ====
Choose the column "Lastname" and the ordering "ASC" (Ascending).


# Pulse en la pestaña "Gráficas".
# Elija el tipo de gráfico "Tarta".
# Escoja la columna "city" tanto para la opción "Nombre" como para la opción "Valor". Pulse el botón "Agregar".


Por último, añada unos cuantos usuarios en Moodle con el país "España" y diferentes ciudades: Madrid, Barcelona, Sevilla, etc. y pruebe a visualizar el informe pulsando en la pestaña "Ver informe".
'''Adding Filters'''


Si ha habilitado las opciones de exportar el informe en alguno de los formatos , podrá descargarlo pulsando sobre los enlaces que aparecen en la parte inferior del informe.
Click on the Filters Tab.


[[#Informe_de_usuarios | Ver pantalla mostrando el informe]]
Add a filter named "User field filter".


=== Crear un informe SQL ===
Choose city.


Puede encontrar un montón de informes SQL aquí: [https://docs.moodle.org/en/ad-hoc_contributed_reports ad-hoc contributed reports]


Puesto que este bloque puede utilizar los informes de consultas SQL personalizadas de Tim Hunt, puede utilizar cualquier consulta.
'''Adding Permissions'''


Recuerde añadir un filtro de tipo "Filtro de fechas" si va a usar informes con valores temporales.
Click on the Permissions Tab.


Para crear un informe de este tipo:
Choose "User field Value".
 
Choose the column "Country", and enter the value "ES".
 
Here you can add more permissions and a logic condition to be achieved.
 
 
'''Adding Calculations'''
 
Click on the Calculations tab.
 
Choose Sum.
 
Choose the column "User module actions".
 
 
'''Adding Plots'''
 
Click on the Plots tab.
 
Choose "Pie".
 
Choose the colum "City" as Name and Value.
 
 
Finally, add a few users in Moodle with the country Spain, and different cities, Madrid, Barcelona, Seville etc. and test the report.
 
You can download the report in differents formats (ods and xls), remember to check these options in the report page.
 
[[blocks/custom_reports/#Users_report | See screenshot]]
 
=== Creating a SQL Report ===
 
You can find a lot of SQL Reports here: [[ad-hoc contributed reports]]
 
Since this block supports Tim Hunt's CustomSQL Queries Reports, you can use any query.
 
Remember to add a "Time filter" if you are going to use reports with time tokens.
 
 
First of all, install the block.
 
Go to the course where the report will be created.
 
Add an instance of the Custom Reports block.
 
Click on "Manage reports".
 
Click on "Add report
 
Enter a name, description, choose "SQL" as Type of Report
 
The report will be saved and you redirect to the firs Tab named "Custom SQL"
 
Add this query (''Courses activity''):


# Pulse en el enlace "Gestionar informes" del bloque de informes personalizados
# Pulse en "Añadir informe".
# Introduzca un nombre y una descripción para el informe y seleccione "Informe SQL" como el tipo del informe.
# Opcionalmente puede marcar las casillas "Exportar en formato ODS" y "Exportar en formato XLS" si desea poder exportar el informe en alguno de estos formatos.
# Pulse el botón "Agregar".
# Se guardará el informe y se le redirigirá a la pestaña denominada "Sentencia SQL".
# Añada esta consulta (''Actividad de los cursos''):
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id
GROUP BY courseId
GROUP BY courseId
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
y pulse el botón "Guardar cambios".
# Vaya a la pestaña "Cálculos".
# Añada un cálculo de tipo "Suma" y escoja la columna "hits". Pulse el botón "Agregar".
# Vaya a la pestaña "Gráficas".
# Elija el tipo de gráfico "Tarta".
# Escoja la columna "hits" tanto para la opción "Nombre" como para la opción "Valor". Pulse el botón "Agregar".
# Pruebe a visualizar el informe pulsando en la pestaña "Ver informe".


Ahí lo tiene, un informe con una gráfica y cálculos basados en una consulta SQL.
Go to Calculations Tab
 
Add a Sum calculation, choose the hits column


Puede añadir un filtro de cursos, es muy sencillo:


# Vaya a la pestaña "Filtros" y añada un filtro de tipo "Cursos".
Go to Plot
# Edite la consulta SQL y ponga lo siguiente:
 
Add a Pie graph, choosing coursename as Name and hits as value
 
So, here you have, a report with a Graph and calculations based on a SQL Query.
 
 
You can add a Course filter, is very easy:
 
Go to filters, choose Courses
 
Edit the Custom SQL query:
 
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
%%FILTER_COURSES:l.course%%  
%%FILTER_COURSES:l.course%%  
Line 175: Line 238:
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
Observe que estamos añadiendo un token llamado %%FILTER_COURSES:l.courseid%%
# Vaya a la pestaña "Ver informe" y verá un filtro de cursos. Elija un curso y pulse en "Añadir" para ver el informe filtrado por ese curso.


También puede añadir un filtro de tipo "Filtro de fechas" para filtrar por fecha de inicio y fin:
Note that we are adding a token called: %%FILTER_COURSES:l.courseid%%
 
Go to View report, and you will see a Courses Filter, choose a Course and click on Add, here you have a report filtered.
 
 
You cand add also, and Starttime and endtime filter
 
Go to filters, choose Stard / End date filter
 
Go to Custom SQL tab, this is the new query:


# Vaya a la pestaña "Filtros" y añada un filtro de tipo "Filtro de fechas".
# Edite la consulta SQL y ponga lo siguiente:
<code sql>
<code sql>
SELECT COUNT(l.id) AS hits, l.course courseId, c.fullname coursename
SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id  
%%FILTER_COURSES:l.course%%  
%%FILTER_COURSES:l.course%%  
Line 190: Line 258:
ORDER BY hits DESC
ORDER BY hits DESC
</code>
</code>
Observe que estamos añadiendo un token llamado %%FILTER_STARTTIME:l.time:>%% %%FILTER_ENDTIME:l.time:<%%
# Vaya a la pestaña "Ver informe" y verá también un filtro para indicar la fecha de inicio y fin a usar para el informe.


[[#Informe_SQL | Ver pantalla mostrando el informe]]


== Opciones avanzadas ==
Go to View report, now you can filter by time also
=== Plantillas ===
 
[[blocks/custom_reports/#SQL_report | See screenshot]]
 
 
== Advanced options ==


Se puede personalizar el informe usando una plantilla. Sólo hace falta ir a la pestaña llamada "Plantilla" y habilitarla, y a continuación rellenar cada una de las partes de la plantilla (cabecera, plantilla para un registro y pie)


Este es un ejemplo de código HTML para visualizar una lista de usuarios:
=== Templates ===


Cabecera:
You can customize the report output using a template.
 
Just enable the Template option in the same name tab.
 
This is an example html code for displaying a list of users:
 
Header:


<code html4strict>
<code html4strict>
Line 211: Line 285:
</code>
</code>


Plantilla para un registro:
Record:


<code html4strict>
<code html4strict>
<table width="100%">
<table width="100%">
<tr>
<tr>
<td><img src="http://tu.sitio.moodle.es/user/pix.php/[[id]]/f1.jpg"></td>
<td><img src="http://yourmoodle.com/user/pix.php/[[id]]/f1.jpg"></td>
<td><h2>[[firstname]] [[lastname]]</h2>
<td><h2>[[Firstname]] [[Lastname]]</h2>
Ciudad: [[city]]
City: [[City]]
</td>
</td>
</tr>
</tr>
Line 225: Line 299:
</code>
</code>


Pie:
Footer:


<code html4strict>
<code html4strict>
Line 237: Line 311:
</code>
</code>


=== Informes incrustados ===
=== Embedded reports ===
Un informe incrustado consiste en un juego de columnas de un informe que están incrustadas entro.
 
A embedded report consists in a report's set of columns that are embeeded in other report.
 
You can embed a user report into a course report, in this case, the resulting rows will be expanded duplicating each row for each user.


Por ejemplo, puede incrustar un informe de usuario en un informe de curso. En este caso, las filas resultantes del curso se expandirán duplicando cada fila para cada usuario.
Imaging you have a courses report, you can embed a user report, every row of the course report will be cloned for each user.


Para incrustar un informe, simplemente añada una nueva columna de tipo "Columna de otro informe". Aparecerá una lista de informes existentes. Una vez seleccionado uno aparecerá la lista de columnas de dicho informe para que podamos escoger la deseada.
To embed a report just add a "Other report" column, a list of your reports will be showed.


Dentro de un informe de curso se puede incrustar un informe de usuario y viceversa. No es posible sin embargo incrustar informes de curso dentro de informes de curso, o informes de usuario dentro de informes de usuario.
Inside a course report you can embed a user report and the other way.


== Documentación para desarrolladores ==
== Developers documentation ==


Es muy fácil crear nuevos tipos de informes, componentes y plugins.
It's very easy to create new report types, components and plugins.


'''Informe''': Un informe es un directorio ubicado dentro de /reports (con respecto al directorio de instalación del bloque). Este directorio contiene un fichero llamado report.class.php con la definición de la clase hija que extiende de report_base.
'''Report''': A report plugin is a folder located at /report.  
This folder contains a .class.php file with the child - class of the report_base.


Sólo necesita modificar unos pocos métodos para añadir un nuevo tipo de informe. Por favor, eche una ojeada a cualquiera de los informes existentes. El informe SQL es un ejemplo de un informe no típico, mientras que los informes de usuarios y cursos son informes estándar.
You only need to modify a few methos to add a new report type.
Please, take a look to any of the current reports. The SQL report is an example of a non-typical report,  
meanwhile the users and courses reports are standard reports.


La mejor manera de crear un nuevo informe es duplicando uno existente.
The best way to create a report is duplicate an existing one.


'''Componente''': Un componente es parte de un informe, y puede ser usado por más de un informe. Además es un directorio ubicado dentro de /components (con respecto al directorio de instalación del bloque). Este directorio contiene un fichero llamado component.class.php con la definición de la clase hija que extiende de component_base.


El componente princial es el componente llamado "columns", que se usa para añadir las columnas de un informe. Otros componentes son los filtros, permisos, gráficas, cálculos, etc.
'''Component''': A component is part of a report, a component may be used by more than one report.
The main Component is the component Columns, that is used to add the columns of a report.


La mejor manera de crear un nuevo componente es duplicando uno existente.
Others components are filters, permissions, plot, calculations..


'''Plugin''': Un plugin es un módulo de un componente. Además es un directorio ubicado dentro de /components/nombre-del-componente/. Este directorio contiene un fichero llamado plugin.class.php con la definición de la clase hija que extiende de plugin_base.
The best way to create a component is duplicate an existing one.


Por ejemplo, el componente columna tiene unos pocos plugins (coursefield, userfield, etc..).


Un plugin funciona normalmente para un único tipo de informe, pero existen plugins que funcionan para más de un tipo de informe.
'''Plugin''': A plugin is a component module. The component column has a few of plugins (coursefield, userfield, etc..)
A plugins works usually for an unique report, but there are plugins that works for more than one report.
The best way to create a plugin is duplicate an existing one.


La mejor manera de crear un nuevo plugin es duplicando uno existente.


== Créditos ==
== Credits ==
Juan Leyva [http://moodle.org/user/view.php?id=49568&course=1 Perfil de Moodle]
 
Juan Leyva [http://moodle.org/user/view.php?id=49568&course=1 Moodle profile]
 
[http://twitter.com/jleyvadelgado Follow me in Twitter]


[http://twitter.com/jleyvadelgado Sígueme en Twitter]
[[Category:Contributed code]]
[[Category:Contributed code]]


== Pantallazos ==
== Screenshots ==
=== Informe de usuarios ===
 
=== Users report ===
[[Image:block_custom_reports_sample_user_report.png|600px]]
[[Image:block_custom_reports_sample_user_report.png|600px]]


=== Informe SQL ===
 
=== SQL report ===
[[Image:block_custom_reports_sample_sql_report.png|600px]]
[[Image:block_custom_reports_sample_sql_report.png|600px]]


[[en:blocks/configurable_reports]]
[[es:blocks/configurable_reports/]]

Revision as of 19:33, 13 October 2010

Installation

  1. Download the Custom Reports installation file and unzip it to the \blocks directory in your Moodle folder.
  2. Login to Moodle as Administrator and click Notifications under Site Administration.


For more information see Installing contributed modules or plugins

Overview

This block is a Moodle custom reports builder.

It is designed in a modular way to allow developers to create new plugins in less than an hour.


Who can create custom reports?

Anyone with block, managereports or manageownreports permissions at SITE level or COURSE level.


What type of reports can I create?

- Courses reports, with information regarding courses.

- Users reports, with information regarding users and their activity in a course.

- Custom SQL Reports, custom SQL queries. This block can use the same SQL queries that Tim Hunt's Custom SQL queries plugin.

Note for developers: You can create your own type of reports.


Who can view the reports?

When you create a report you can select which users can view it.

The reports are displayed in a block in the course or site frontpage.

Creating a report

This is a very simple process.

If you are going to create a report for a course, you have to add the block in the course and click in the "Manage reports" link.

On the other hand, for site reports, add the block in the frontpage and click in the "Manage reports" link.

You must enter a name, an optional description, and you have to choose the type of report, pagination and exports formats.

Depending on the report choosen, there will be more or less tabs. These are the tabs for the courses and users report:

Columns: Here you can choose the differents columns of your report depending on the type of report. (Course Name, User firstname, etc..)

Conditions: Here you can define the conditions (i.e, only courses from this category, only users from Spain, etc.)

Ordering: Here you can choose how to order the report using fields and directions.

Filters: Here you can choose which filters will be displayed.

Template: You can modify the report's layout by creating a template.

Permissions: Here you can choose who can view a report.

Calculations: Here you can add calculations for columns, i.e: average of number of users enrolled in courses

Plots: Here you can add graphs to your report based on the report columns and values.

View report: Self explanatory

Tutorial

Creating a users' report

Requirements: Users from Spain, but no from Madrid, in this course. This report can be viewed only by users from Spain. A filter based on the user's city must be displayed. A pie plot showing the users' cities is required. A calculation table showing the total forum post views is required. The report must be order by users' lastname.


Let's see how easy it is!

First of all, install the block.

Go to the course where the report will be created.

Add an instance of the Custom Reports block.

Click on "Manage reports"

Click on "Add report"

Enter a name, a description and choose "Users report" as Type of Report

The report will be saved and you will be redirected to the first Tab named "Columns".


Adding Columns

Here you can define the report table properties, width, align, cell padding, cell spacing, etc.. Add a Column called "User profile field"

Choose the field "firstname" and enter a name for the column in the text field. You can leave blank the rest of elements.

Repit the process above for the lastname and city fields.

Add a Column called "User module actions".

Choose a module from the list, in this example, a forum.


Adding Conditions

Click on the Conditions Tab.

Add a Condition named "User field Condition".

Choose the column "Country", the Operator "=", and enter the value "ES" (this is the international code for Spain as Moodle stores it).

Add a Condition named "User field Condition".

Choose the column "city", the Operator "<>", and enter the value "Madrid".

Add a Condition named "Users in current report course".

These are the main conditions of the reports. Note that at the bottom there is a text box called condition, with this text:

"c2 and c1 and c3"

Here you can define a logic condition, in this case, we don't need to edit this condition but you can create complex expressions like:

(c1 and c2) or (c4 and c3)


Adding Ordering

Click on the Ordering Tab.

Add a ordering named "User field ordering".

Choose the column "Lastname" and the ordering "ASC" (Ascending).


Adding Filters

Click on the Filters Tab.

Add a filter named "User field filter".

Choose city.


Adding Permissions

Click on the Permissions Tab.

Choose "User field Value".

Choose the column "Country", and enter the value "ES".

Here you can add more permissions and a logic condition to be achieved.


Adding Calculations

Click on the Calculations tab.

Choose Sum.

Choose the column "User module actions".


Adding Plots

Click on the Plots tab.

Choose "Pie".

Choose the colum "City" as Name and Value.


Finally, add a few users in Moodle with the country Spain, and different cities, Madrid, Barcelona, Seville etc. and test the report.

You can download the report in differents formats (ods and xls), remember to check these options in the report page.

See screenshot

Creating a SQL Report

You can find a lot of SQL Reports here: ad-hoc contributed reports

Since this block supports Tim Hunt's CustomSQL Queries Reports, you can use any query.

Remember to add a "Time filter" if you are going to use reports with time tokens.


First of all, install the block.

Go to the course where the report will be created.

Add an instance of the Custom Reports block.

Click on "Manage reports".

Click on "Add report

Enter a name, description, choose "SQL" as Type of Report

The report will be saved and you redirect to the firs Tab named "Custom SQL"

Add this query (Courses activity):

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id GROUP BY courseId ORDER BY hits DESC

Go to Calculations Tab

Add a Sum calculation, choose the hits column


Go to Plot

Add a Pie graph, choosing coursename as Name and hits as value

So, here you have, a report with a Graph and calculations based on a SQL Query.


You can add a Course filter, is very easy:

Go to filters, choose Courses

Edit the Custom SQL query:

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id %%FILTER_COURSES:l.course%% GROUP BY courseId ORDER BY hits DESC

Note that we are adding a token called: %%FILTER_COURSES:l.courseid%%

Go to View report, and you will see a Courses Filter, choose a Course and click on Add, here you have a report filtered.


You cand add also, and Starttime and endtime filter

Go to filters, choose Stard / End date filter

Go to Custom SQL tab, this is the new query:

SELECT COUNT(l.id) hits, l.course courseId, c.fullname coursename FROM prefix_log l INNER JOIN prefix_course c ON l.course = c.id %%FILTER_COURSES:l.course%% %%FILTER_STARTTIME:l.time:>%% %%FILTER_ENDTIME:l.time:<%% GROUP BY courseId ORDER BY hits DESC


Go to View report, now you can filter by time also

See screenshot


Advanced options

Templates

You can customize the report output using a template.

Just enable the Template option in the same name tab.

This is an example html code for displaying a list of users:

Header:

##reportname##

Record:

<img src="http://yourmoodle.com/user/pix.php/id/f1.jpg">

Firstname Lastname

City: City


Footer:

    1. graphs##



    1. exportoptions##

Embedded reports

A embedded report consists in a report's set of columns that are embeeded in other report.

You can embed a user report into a course report, in this case, the resulting rows will be expanded duplicating each row for each user.

Imaging you have a courses report, you can embed a user report, every row of the course report will be cloned for each user.

To embed a report just add a "Other report" column, a list of your reports will be showed.

Inside a course report you can embed a user report and the other way.

Developers documentation

It's very easy to create new report types, components and plugins.

Report: A report plugin is a folder located at /report. This folder contains a .class.php file with the child - class of the report_base.

You only need to modify a few methos to add a new report type. Please, take a look to any of the current reports. The SQL report is an example of a non-typical report, meanwhile the users and courses reports are standard reports.

The best way to create a report is duplicate an existing one.


Component: A component is part of a report, a component may be used by more than one report. The main Component is the component Columns, that is used to add the columns of a report.

Others components are filters, permissions, plot, calculations..

The best way to create a component is duplicate an existing one.


Plugin: A plugin is a component module. The component column has a few of plugins (coursefield, userfield, etc..) A plugins works usually for an unique report, but there are plugins that works for more than one report. The best way to create a plugin is duplicate an existing one.


Credits

Juan Leyva Moodle profile

Follow me in Twitter

Screenshots

Users report

block custom reports sample user report.png


SQL report

block custom reports sample sql report.png