mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-20 14:43:49 +00:00
prepare for merging doc into mono-repository
This commit is contained in:
314
docs/source/development/access_control_model.rst
Normal file
314
docs/source/development/access_control_model.rst
Normal file
@@ -0,0 +1,314 @@
|
||||
.. Copyright (C) 2015 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Access controle model
|
||||
**********************
|
||||
|
||||
.. contents:: Table of content
|
||||
:local:
|
||||
|
||||
Concepts
|
||||
========
|
||||
|
||||
Every time an entity is created, viewed or updated, the software check if the user has the permission to make this action. The decision is made with three parameters :
|
||||
|
||||
- the type of entity ;
|
||||
- the entity's center ;
|
||||
- the entity'scope
|
||||
|
||||
The user must be granted access to the action on this particular entity, with this scope and center.
|
||||
|
||||
From an user point of view
|
||||
--------------------------
|
||||
|
||||
The software is design to allow fine tuned access rights for complicated installation and team structure. The administrators may also decide that every user has the right to see all resources, where team have a more simple structure.
|
||||
|
||||
Here is an overview of the model.
|
||||
|
||||
Chill can be multi-center
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Chill is designed to be installed once for social center who work with multiple teams separated, or for social services's federation who would like to share the same installation of the software for all their members.
|
||||
|
||||
This was required for cost reduction, but also to ease the generation of statistics agregated across federation's members, or from the central unit of the social center with multiple teams.
|
||||
|
||||
Otherwise, it is not required to create multiple center: Chill can also work for one center.
|
||||
|
||||
Obviously, users working in the different centers are not allowed to see the entities (_persons_, _reports_, _activities_) of other centers. But users may be attached to multiple centers: consequently they will be able to see the entities of the multiple centers they are attached to.
|
||||
|
||||
Inside center, scope divide team
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Users are attached to one or more center and, inside to those center, there may exists differents scopes. The aim of those _scopes_ is to divide the whole team of social worker amongst different departement, for instance: the social team, the psychologist team, the nurse team, the administrative team, ... Each team is granted of different rights amongst scope. For instance, the social team may not see the _activities_ of the psychologist team. The administrative team may see the date & time's activities, but is not allowed to see the detail of those entities (the personal notes, ...).
|
||||
|
||||
The administrator is responsible of creating those scopes and team. *He may also decide to not define a division inside his team*: he creates only one scope and all entities will belong to this scope, all users will be able to see all entities.
|
||||
|
||||
As entities have only one scopes, if some entities must be shared across two different teams, the administrator will have to create a scope *shared* by two different team, and add the ability to create, view, or update this scope to those team.
|
||||
|
||||
Example: if some activities must be seen and updated between nurses and psychologists, the administrator will create a scope "nurse and psy" and add the ability for both team "nurse" and "psychologist" to "create", "see", and "update" the activities belonging to scope "nurse and psy".
|
||||
|
||||
The concepts translated into code
|
||||
-----------------------------------
|
||||
|
||||
.. figure:: /_static/access_control_model.png
|
||||
|
||||
Schema of the access control model
|
||||
|
||||
Chill handle **entities**, like *persons*, *reports* (associated to *persons*), *activities* (also associated to *_persons*), ... On creation, those entities are linked to one center and, eventually, to one scope. They implements the interface `HasCenterInterface`.
|
||||
|
||||
.. note::
|
||||
|
||||
Somes entities are linked to a center through the entity they are associated with. For instance, *activities* or *reports* are associated to a *person*, and the person is associated to a *center*. The *report*'s *center* is always the *person*'s *center*.
|
||||
|
||||
Entities may be associated with a scope. In this case, they implement the `HasScopeInterface`.
|
||||
|
||||
.. note::
|
||||
|
||||
Currently, only the *person* entity is not associated with a scope.
|
||||
|
||||
At each step of his lifetime (creation, view of the entity and eventually of his details, update and, eventually, deletion), the right of the user are checked. To decide wether the user is granted right to execute the action, the software must decide with those elements :
|
||||
|
||||
- the entity's type;
|
||||
- the entity's center ;
|
||||
- the entity's scope, if it exists,
|
||||
- and, obviously, a string representing the action
|
||||
|
||||
All those action are executed through symfony voters and helpers.
|
||||
|
||||
How to check authorization ?
|
||||
----------------------------
|
||||
|
||||
Just use the symfony way-of-doing, but do not forget to associate the entity you want to check access. For instance, in controller :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
class MyController extends Controller
|
||||
{
|
||||
|
||||
public function viewAction($entity)
|
||||
{
|
||||
$this->denyAccessUnlessGranted('CHILL_ENTITY_SEE', $entity);
|
||||
|
||||
//... go on with this action
|
||||
}
|
||||
}
|
||||
|
||||
And in template :
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{{ if is_granted('CHILL_ENTITY_SEE', entity) %}print something{% endif %}
|
||||
|
||||
Retrieving reachable scopes and centers
|
||||
----------------------------------------
|
||||
|
||||
The class :class:`Chill\\MainBundle\\Security\\Authorization\\AuthorizationHelper` helps you to get centers and scope reachable by a user.
|
||||
|
||||
Those methods are intentionnaly build to give information about user rights:
|
||||
|
||||
- getReachableCenters: to get reachable centers for a user
|
||||
- getReachableScopes : to get reachable scopes for a user
|
||||
|
||||
.. note::
|
||||
|
||||
The service is reachable through the Depedency injection with the key `chill.main.security.authorization.helper`. Example :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$helper = $container->get('chill.main.security.authorization.helper');
|
||||
|
||||
.. todo::
|
||||
|
||||
Waiting for a link between our api and this doc, we invite you to read the method signatures `here <https://github.com/Chill-project/Main/blob/add_acl/Security/Authorization/AuthorizationHelper.php>`_
|
||||
|
||||
Adding your own roles
|
||||
=====================
|
||||
|
||||
Extending Chill will requires you to define your own roles and rules for your entities. You will have to define your own voter to do so.
|
||||
|
||||
To create your own roles, you should:
|
||||
|
||||
* implement your own voter. This voter will have to extends the :class:`Chill\\MainBundle\\Security\\AbstractChillVoter`. As defined by Symfony, this voter must be declared as a service and tagged with `security.voter`;
|
||||
* declare the role through implementing a service tagged with `chill.role` and implementing :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface`.
|
||||
|
||||
.. note::
|
||||
|
||||
Both operation may be done through a simple class: you can implements :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface` and :class:`Chill\\MainBundle\\Security\\AbstractChillVoter` on the same class. See live example: :class:`Chill\\ActivityBundle\\Security\\Authorization\\ActivityVoter`, and similar examples in the `PersonBundle` and `ReportBundle`.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`How to Use Voters to Check User Permissions <http://symfony.com/doc/current/cookbook/security/voters_data_permission.html>`_
|
||||
|
||||
From the symfony cookbook
|
||||
|
||||
`New in Symfony 2.6: Simpler Security Voters <http://symfony.com/blog/new-in-symfony-2-6-simpler-security-voters>`_
|
||||
|
||||
From the symfony blog
|
||||
|
||||
|
||||
Declare your role
|
||||
------------------
|
||||
|
||||
To declare new role, implement the class :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface`.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
interface ProvideRoleInterface
|
||||
{
|
||||
/**
|
||||
* return an array of role provided by the object
|
||||
*
|
||||
* @return string[] array of roles (as string)
|
||||
*/
|
||||
public function getRoles();
|
||||
|
||||
/**
|
||||
* return roles which doesn't need
|
||||
*
|
||||
* @return string[] array of roles without scopes
|
||||
*/
|
||||
public function getRolesWithoutScope();
|
||||
}
|
||||
|
||||
|
||||
Then declare your service with a tag `chill.role`. Example :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
your_service:
|
||||
class: Chill\YourBundle\Security\Authorization\YourVoter
|
||||
tags:
|
||||
- { name: chill.role }
|
||||
|
||||
|
||||
Example of an implementation of :class:`Chill\\MainBundle\\Security\\ProvideRoleInterface`:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Security\Authorization;
|
||||
|
||||
use Chill\MainBundle\Security\ProvideRoleInterface;
|
||||
|
||||
class PersonVoter implements ProvideRoleInterface
|
||||
{
|
||||
const CREATE = 'CHILL_PERSON_CREATE';
|
||||
const UPDATE = 'CHILL_PERSON_UPDATE';
|
||||
const SEE = 'CHILL_PERSON_SEE';
|
||||
|
||||
public function getRoles()
|
||||
{
|
||||
return array(self::CREATE, self::UPDATE, self::SEE);
|
||||
}
|
||||
|
||||
public function getRolesWithoutScope()
|
||||
{
|
||||
return array(self::CREATE, self::UPDATE, self::SEE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Implement your voter
|
||||
--------------------
|
||||
|
||||
Inside this class, you might use the :class:`Chill\\MainBundle\\Security\\Authorization\\AuthorizationHelper` to check permission (do not re-invent the wheel). This is a real-world example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\ReportBundle\Security\Authorization;
|
||||
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
|
||||
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
|
||||
|
||||
|
||||
class ReportVoter extends AbstractChillVoter
|
||||
{
|
||||
const CREATE = 'CHILL_REPORT_CREATE';
|
||||
const SEE = 'CHILL_REPORT_SEE';
|
||||
const UPDATE = 'CHILL_REPORT_UPDATE';
|
||||
|
||||
/**
|
||||
*
|
||||
* @var AuthorizationHelper
|
||||
*/
|
||||
protected $helper;
|
||||
|
||||
public function __construct(AuthorizationHelper $helper)
|
||||
{
|
||||
$this->helper = $helper;
|
||||
}
|
||||
|
||||
protected function getSupportedAttributes()
|
||||
{
|
||||
return array(self::CREATE, self::SEE, self::UPDATE);
|
||||
}
|
||||
protected function getSupportedClasses()
|
||||
{
|
||||
return array('Chill\ReportBundle\Entity\Report');
|
||||
}
|
||||
protected function isGranted($attribute, $report, $user = null)
|
||||
{
|
||||
if (! $user instanceof \Chill\MainBundle\Entity\User){
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->helper->userHasAccess($user, $report, $attribute);
|
||||
}
|
||||
}
|
||||
|
||||
Then, you will have to declare the service and tag it as a voter :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
services:
|
||||
chill.report.security.authorization.report_voter:
|
||||
class: Chill\ReportBundle\Security\Authorization\ReportVoter
|
||||
arguments:
|
||||
- "@chill.main.security.authorization.helper"
|
||||
tags:
|
||||
- { name: security.voter }
|
||||
|
||||
|
||||
Adding role hierarchy
|
||||
---------------------
|
||||
|
||||
You should prepend Symfony's security component directly from your code.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\ReportBundle\DependencyInjection;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\Config\FileLocator;
|
||||
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
|
||||
use Symfony\Component\DependencyInjection\Loader;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
use Chill\MainBundle\DependencyInjection\MissingBundleException;
|
||||
|
||||
/**
|
||||
* This is the class that loads and manages your bundle configuration
|
||||
*
|
||||
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
|
||||
*/
|
||||
class ChillReportExtension extends Extension implements PrependExtensionInterface
|
||||
{
|
||||
public function prepend(ContainerBuilder $container)
|
||||
{
|
||||
$this->prependRoleHierarchy($container);
|
||||
}
|
||||
|
||||
protected function prependRoleHierarchy(ContainerBuilder $container)
|
||||
{
|
||||
$container->prependExtensionConfig('security', array(
|
||||
'role_hierarchy' => array(
|
||||
'CHILL_REPORT_UPDATE' => array('CHILL_REPORT_SEE'),
|
||||
'CHILL_REPORT_CREATE' => array('CHILL_REPORT_SEE')
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
104
docs/source/development/assets.rst
Normal file
104
docs/source/development/assets.rst
Normal file
@@ -0,0 +1,104 @@
|
||||
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _forms:
|
||||
|
||||
Assets
|
||||
#######
|
||||
|
||||
The Chill assets (js, css, images, …) can be managed by `Webpack Encore`_, which is a thin wrapper for `Webpack`_ in Symfony applications.
|
||||
|
||||
Installation
|
||||
************
|
||||
|
||||
Webpack Encore needs to be run in a Node.js environment, using the Yarn package manager. This Node.js environment can be set up using a node docker image. The bash script `docker-node.sh` set up a Node.js environment with an adequate configuration. Launch this container by typing:
|
||||
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ bash docker-node.sh
|
||||
|
||||
In this NodeJS environment, install all the assets required by Chill with:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
node@b91cab4f7cfc:/app$ yarn install
|
||||
|
||||
This command will install all the packages that are listed in `package.json`.
|
||||
|
||||
Any further required dependencies can be installed using the Yarn package. For instance, jQuery is installed by:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
node@b91cab4f7cfc:/app$ yarn add jquery --dev
|
||||
|
||||
|
||||
Usage
|
||||
*****
|
||||
|
||||
Organize your assets
|
||||
--------------------
|
||||
|
||||
Chill assets usually lives under the `/Resources/public` folder of each Chill bundle. The Webpack configuration set up in `webpack.config.js` automatically loads the required assets from the Chill bundles that are used.
|
||||
|
||||
For adding your own assets to Webpack, you must add an entry in the `webpack.config.js` file. For instance, the following entry will output a file `main.js` collecting the js code (and possibly css, image, etc.) from `./assets/main.js`.
|
||||
|
||||
.. code-block:: js
|
||||
|
||||
.addEntry('main', './assets/main.js')
|
||||
|
||||
To gather the css files, simply connect them to your js file, using `require`. The css file is seen as a dependency of your js file. :
|
||||
|
||||
.. code-block:: js
|
||||
|
||||
// assets/js/main.js
|
||||
require('../css/app.css');
|
||||
|
||||
For finer configuration of webpack encore, we refer to the above-linked documentation.
|
||||
|
||||
|
||||
Compile the assets
|
||||
------------------
|
||||
|
||||
To compile the assets, run this line in the NodeJS container:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
node@b91cab4f7cfc:/app$ yarn run encore dev
|
||||
|
||||
While developing, you can tell Webpack Encore to continuously watch the files you are modifying:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
node@b91cab4f7cfc:/app$ yarn run encore dev --watch
|
||||
|
||||
|
||||
Use the assets in the templates
|
||||
--------------------------------
|
||||
|
||||
Any entry defined in the webpack.config.js file can be linked to your application using the symfony `asset` helper:
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<head>
|
||||
...
|
||||
<link rel="stylesheet" href="{{ asset('build/app.css') }}">
|
||||
</head>
|
||||
<body>
|
||||
...
|
||||
<script src="{{ asset('build/app.js') }}"></script>
|
||||
</body>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.. _Webpack Encore: https://www.npmjs.com/package/@symfony/webpack-encore
|
||||
.. _Webpack: https://webpack.js.org/
|
34
docs/source/development/create-a-new-bundle.rst
Normal file
34
docs/source/development/create-a-new-bundle.rst
Normal file
@@ -0,0 +1,34 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _create-new-bundle:
|
||||
|
||||
Create a new bundle
|
||||
*******************
|
||||
|
||||
Create your own bundle is not a trivial task.
|
||||
|
||||
The easiest way to achieve this is seems to be :
|
||||
|
||||
1. Prepare a fresh installation of the chill project, in a new directory
|
||||
2. Create a new bundle in this project, in the src directory
|
||||
3. Initialize a git repository **at the root bundle**, and create your initial commit.
|
||||
4. Register the bundle with composer/packagist. If you do not plan to distribute your bundle with packagist, you may use a custom repository for achieve this [#f1]_
|
||||
5. Move to a development installation, made as described in the :ref:`installation-for-development` section, and add your new repository to the composer.json file
|
||||
6. Work as :ref:`usual <editing-code-and-commiting>`
|
||||
|
||||
.. warning::
|
||||
|
||||
This part of the doc is not yet tested
|
||||
|
||||
TODO
|
||||
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] Be aware that we use the Affero GPL Licence, which ensure that all users must have access to derivative works done with this software.
|
522
docs/source/development/crud.rst
Normal file
522
docs/source/development/crud.rst
Normal file
@@ -0,0 +1,522 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _crud:
|
||||
|
||||
CRUD
|
||||
####
|
||||
|
||||
Chill provide an API to create a basic CRUD.
|
||||
|
||||
One can follow those steps to create a CRUD for one entity:
|
||||
|
||||
1. create your model and your form ;
|
||||
2. configure the crud ;
|
||||
3. customize the templates if required ;
|
||||
4. customize some steps of the controller if required ;
|
||||
|
||||
|
||||
An example with the ``ClosingMotive`` (PersonBundle) in the admin part of Chill:
|
||||
|
||||
Auto-loading the routes
|
||||
***********************
|
||||
|
||||
Ensure that those lines are present in your file `app/config/routing.yml`:
|
||||
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_cruds:
|
||||
resource: 'chill_main_crud_route_loader:load'
|
||||
type: service
|
||||
|
||||
|
||||
|
||||
Create your model
|
||||
*****************
|
||||
|
||||
Create your model on the usual way (in this example, ORM informations are stored in yaml file):
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
|
||||
/**
|
||||
* ClosingMotive give an explanation why we closed the Accompanying period
|
||||
*/
|
||||
class ClosingMotive
|
||||
{
|
||||
/**
|
||||
* @var integer
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
private $active = true;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var self
|
||||
*/
|
||||
private $parent = null;
|
||||
|
||||
/**
|
||||
* child Accompanying periods
|
||||
*
|
||||
* @var Collection
|
||||
*/
|
||||
private $children;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var float
|
||||
*/
|
||||
private $ordering = 0.0;
|
||||
|
||||
|
||||
// getters and setters come here
|
||||
|
||||
}
|
||||
|
||||
The form:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Chill\PersonBundle\Form\Type\ClosingMotivePickerType;
|
||||
use Chill\MainBundle\Form\Type\TranslatableStringFormType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\NumberType;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
class ClosingMotiveType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options)
|
||||
{
|
||||
$builder
|
||||
->add('name', TranslatableStringFormType::class, [
|
||||
'label' => 'Nom'
|
||||
])
|
||||
->add('active', CheckboxType::class, [
|
||||
'label' => 'Actif ?',
|
||||
'required' => false
|
||||
])
|
||||
->add('ordering', NumberType::class, [
|
||||
'label' => 'Ordre d\'apparition',
|
||||
'required' => true,
|
||||
'scale' => 5
|
||||
])
|
||||
->add('parent', ClosingMotivePickerType::class, [
|
||||
'label' => 'Parent',
|
||||
'required' => false,
|
||||
'placeholder' => 'closing_motive.any parent',
|
||||
'multiple' => false,
|
||||
'only_leaf' => false
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver)
|
||||
{
|
||||
$resolver
|
||||
->setDefault('class', \Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive::class)
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
Configure the crud
|
||||
******************
|
||||
|
||||
The crud is configured using the key ``crud`` under ``chill_main``
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_main:
|
||||
cruds:
|
||||
-
|
||||
# the class which is concerned by the CRUD
|
||||
class: '\Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive::class'
|
||||
# give a name for the crud. This will be used internally
|
||||
name: closing_motive
|
||||
# add a base path for the
|
||||
base_path: /admin/closing-motive
|
||||
# this is the form class
|
||||
form_class: 'Chill\PersonBundle\Form\ClosingMotiveType::class'
|
||||
# you can override the controller to configure some parts
|
||||
# if you do not configure anything here, the default CRUDController will be used
|
||||
controller: 'Chill\PersonBundle\Controller\AdminClosingMotiveController::class'
|
||||
# this is a list of action you can configure
|
||||
# by default, the actions `index`, `view`, `new` and `edit` are automatically create
|
||||
# you can add more actions or configure some details about them
|
||||
actions:
|
||||
index:
|
||||
# the default template for index is very poor,
|
||||
# you will need to override it
|
||||
template: '@ChillPerson/ClosingMotive/index.html.twig'
|
||||
# the role required for this role
|
||||
role: ROLE_ADMIN
|
||||
new:
|
||||
role: ROLE_ADMIN
|
||||
# by default, the template will only show the form
|
||||
# you can override it
|
||||
template: '@ChillPerson/ClosingMotive/new.html.twig'
|
||||
edit:
|
||||
role: ROLE_ADMIN
|
||||
template: '@ChillPerson/ClosingMotive/edit.html.twig'
|
||||
|
||||
To leave the bundle auto-configure the ``chill_main`` bundle, you can `prepend the configuration of the ChillMain Bundle <https://symfony.com/doc/current/bundles/prepend_extension.html>`_:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
|
||||
class ChillPersonExtension extends Extension implements PrependExtensionInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function load(array $configs, ContainerBuilder $container)
|
||||
{
|
||||
// skipped here
|
||||
}
|
||||
|
||||
|
||||
public function prepend(ContainerBuilder $container)
|
||||
{
|
||||
$this->prependCruds($container);
|
||||
}
|
||||
|
||||
protected function prependCruds(ContainerBuilder $container)
|
||||
{
|
||||
$container->prependExtensionConfig('chill_main', [
|
||||
'cruds' => [
|
||||
[
|
||||
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive::class,
|
||||
'name' => 'closing_motive',
|
||||
'base_path' => '/admin/closing-motive',
|
||||
'form_class' => \Chill\PersonBundle\Form\ClosingMotiveType::class,
|
||||
'controller' => \Chill\PersonBundle\Controller\AdminClosingMotiveController::class,
|
||||
'actions' => [
|
||||
'index' => [
|
||||
'template' => '@ChillPerson/ClosingMotive/index.html.twig',
|
||||
'role' => 'ROLE_ADMIN'
|
||||
],
|
||||
'new' => [
|
||||
'role' => 'ROLE_ADMIN',
|
||||
'template' => '@ChillPerson/ClosingMotive/new.html.twig',
|
||||
],
|
||||
'edit' => [
|
||||
'role' => 'ROLE_ADMIN',
|
||||
'template' => '@ChillPerson/ClosingMotive/edit.html.twig',
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Customize templates
|
||||
*******************
|
||||
|
||||
The current template are quite basic. You can override and extends them.
|
||||
|
||||
For a better inclusion, you can embed them instead of extending them.
|
||||
|
||||
For index. Note that we extend here the `admin` layout, not the default one:
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{% extends '@ChillMain/Admin/layout.html.twig' %}
|
||||
|
||||
{% block admin_content %}
|
||||
{% embed '@ChillMain/CRUD/_index.html.twig' %}
|
||||
{# we customize the table headers #}
|
||||
{% block table_entities_thead_tr %}
|
||||
<th>{{ 'Ordering'|trans }}</th>
|
||||
<th>{{ 'Label'|trans }}</th>
|
||||
<th>{{ 'Active'|trans }}</th>
|
||||
<th> </th>
|
||||
{% endblock %}
|
||||
|
||||
{% block table_entities_tbody %}
|
||||
{# we customize the content of the table #}
|
||||
{% for entity in entities %}
|
||||
<tr>
|
||||
<td>{{ entity.ordering }}</td>
|
||||
<td>{{ entity|chill_entity_render_box }}</td>
|
||||
<td>{{ entity.active }}</td>
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ chill_path_add_return_path('chill_crud_closing_motive_edit', { 'id': entity.id }) }}" class="sc-button bt-edit"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ chill_path_add_return_path('chill_crud_closing_motive_new', { 'parent_id': entity.id } ) }}" class="sc-button bt-new">{{ 'closing_motive.new child'|trans }}</a>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
{% endembed %}
|
||||
{% endblock %}
|
||||
|
||||
For edit template:
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{% extends '@ChillMain/Admin/layout.html.twig' %}
|
||||
|
||||
{% block title %}
|
||||
{% include('@ChillMain/CRUD/_edit_title.html.twig') %}
|
||||
{% endblock %}
|
||||
|
||||
{% block admin_content %}
|
||||
{% as we are in the admin layout, we override the admin content with the CRUD content %}
|
||||
{% embed '@ChillMain/CRUD/_edit_content.html.twig' %}
|
||||
{# we do not have "view" page. We empty the corresponding block #}
|
||||
{% block content_form_actions_view %}{% endblock %}
|
||||
{% endembed %}
|
||||
{% endblock %}
|
||||
|
||||
For new template:
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{% extends '@ChillMain/Admin/layout.html.twig' %}
|
||||
|
||||
{% block title %}
|
||||
{% include('@ChillMain/CRUD/_new_title.html.twig') %}
|
||||
{% endblock %}
|
||||
|
||||
{% block admin_content %}
|
||||
{% embed '@ChillMain/CRUD/_new_content.html.twig' %}
|
||||
{% block content_form_actions_save_and_show %}{% endblock %}
|
||||
{% endembed %}
|
||||
{% endblock %}
|
||||
|
||||
Customize some steps in the controller
|
||||
**************************************
|
||||
|
||||
Some steps may be customized by overriding the default controller and some methods. Here, we will override the way the entity is created, and the ordering of the "index" page:
|
||||
|
||||
* we will associate a parent ClosingMotive to the element if a parameter `parent_id` is found ;
|
||||
* we will order the ClosingMotive by the ``ordering`` property
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Controller;
|
||||
|
||||
use Chill\MainBundle\CRUD\Controller\CRUDController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Chill\MainBundle\Pagination\PaginatorInterface;
|
||||
|
||||
/**
|
||||
* Controller for closing motives
|
||||
*
|
||||
*/
|
||||
class AdminClosingMotiveController extends CRUDController
|
||||
{
|
||||
protected function createEntity($action, Request $request): object
|
||||
{
|
||||
// we first create an entity "the usual way"
|
||||
$entity = parent::createEntity($action, $request);
|
||||
|
||||
if ($request->query->has('parent_id')) {
|
||||
// if we find the parent_id parameter, we add the corresponding
|
||||
// parent to the newly created entity
|
||||
$parentId = $request->query->getInt('parent_id');
|
||||
|
||||
$parent = $this->getDoctrine()->getManager()
|
||||
->getRepository($this->getEntityClass())
|
||||
->find($parentId);
|
||||
|
||||
if (NULL === $parent) {
|
||||
throw $this->createNotFoundException('parent id not found');
|
||||
}
|
||||
|
||||
$entity->setParent($parent);
|
||||
}
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator)
|
||||
{
|
||||
// by default, the query is an instance of QueryBuilder
|
||||
/** @var \Doctrine\ORM\QueryBuilder $query */
|
||||
return $query->orderBy('e.ordering', 'ASC');
|
||||
}
|
||||
}
|
||||
|
||||
How-to and questions
|
||||
********************
|
||||
|
||||
Which role is required for each action ?
|
||||
========================================
|
||||
|
||||
By default, each action will use:
|
||||
|
||||
1. the role defined under the action key ;
|
||||
2. the base role as upper, with the action name appended:
|
||||
|
||||
Example: if the base role is ``CHILL_BUNDLE_ENTITY``, the role will become:
|
||||
|
||||
* ``CHILL_BUNDLE_ENTITY_VIEW`` for the ``view`` action ;
|
||||
* ``CHILL_BUNDLE_ENTITY_INDEX`` for the ``index`` action.
|
||||
|
||||
The entity will be passed to the role:
|
||||
|
||||
* for the ``view`` and ``edit`` action: the entity fetched from database
|
||||
* for the ``new`` action: the entity which is created (you can override default values using
|
||||
* for index action (or if you re-use the ``indexAction`` method: ``null``
|
||||
|
||||
How to add some route and actions ?
|
||||
===================================
|
||||
|
||||
Add them under the action key:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_main:
|
||||
cruds:
|
||||
-
|
||||
# snipped
|
||||
actions:
|
||||
myaction: ~
|
||||
|
||||
The method `myactionAction` will be called by the parameter.
|
||||
|
||||
Inside this action, you can eventually call another internal method:
|
||||
|
||||
* ``indexAction`` for a list of items ;
|
||||
* ``viewAction`` for a view
|
||||
* ``editFormAction`` for an edition
|
||||
* ``createFormAction`` for a creation
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace CSConnectes\SPBundle\Controller;
|
||||
|
||||
use Chill\PersonBundle\CRUD\Controller\OneToOneEntityPersonCRUDController;
|
||||
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
|
||||
use Chill\PersonBundle\Security\Authorization\PersonVoter;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use CSConnectes\SPBundle\Form\CSPersonPersonalSituationType;
|
||||
use CSConnectes\SPBundle\Form\CSPersonDispositifsType;
|
||||
use Symfony\Component\Security\Core\Role\Role;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CSPersonController extends OneToOneEntityPersonCRUDController
|
||||
{
|
||||
public function personalSituationEdit(Request $request, $id)
|
||||
{
|
||||
return $this->formEditAction(
|
||||
'ps_situation_edit',
|
||||
$request,
|
||||
$id,
|
||||
CSPersonPersonalSituationType::class
|
||||
);
|
||||
}
|
||||
|
||||
public function personalSituationView(Request $request, $id): Response
|
||||
{
|
||||
return $this->viewAction('ps_situation_view', $request, $id);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
How to create a CRUD for entities associated to persons
|
||||
=======================================================
|
||||
|
||||
The bundle person provide some controller and template you can override, instead of the ones present in the mainbundle:
|
||||
|
||||
* :code:`Chill\PersonBundle\CRUD\Controller\EntityPersonCRUDController` for entities linked with a one-to-may association to :code:`Person` class ;
|
||||
* :code:`Chill\PersonBundle\CRUD\Controller\OneToOneEntityPersonCRUDController` for entities linked with a one-to-one association to :code:`Person` class.
|
||||
|
||||
There are also template defined under ``@ChillPerson/CRUD/`` namespace.
|
||||
|
||||
Those controller assume that:
|
||||
|
||||
* the entity provide the method :code:`getPerson` and :code:`setPerson` ;
|
||||
* the `index`'s id path will be the id of the person, and the ids in `view` and `edit` path will be the id of the entity ;
|
||||
|
||||
This bundle also use by default the templates inside ``@ChillPerson/CRUD/``.
|
||||
|
||||
|
||||
Reference
|
||||
*********
|
||||
|
||||
Configuration reference
|
||||
=======================
|
||||
|
||||
|
||||
.. code-block:: txt
|
||||
|
||||
chill_main:
|
||||
cruds:
|
||||
|
||||
# Prototype
|
||||
-
|
||||
class: ~ # Required
|
||||
controller: Chill\MainBundle\CRUD\Controller\CRUDController
|
||||
name: ~ # Required
|
||||
base_path: ~ # Required
|
||||
base_role: null
|
||||
form_class: null
|
||||
actions:
|
||||
|
||||
# Prototype
|
||||
name:
|
||||
|
||||
# the method name to call in the route. Will be set to the action name if left empty.
|
||||
controller_action: null # Example: 'action'
|
||||
|
||||
# the path that will be **appended** after the base path. Do not forget to add arguments for the method. Will be set to the action name, including an `{id}` parameter if left empty.
|
||||
path: null # Example: /{id}/my-action
|
||||
|
||||
# the requirements for the route. Will be set to `[ 'id' => '\d+' ]` if left empty.
|
||||
requirements: []
|
||||
|
||||
# the role that will be required for this action. Override option `base_role`
|
||||
role: null
|
||||
|
||||
# the template to render the view
|
||||
template: null
|
||||
|
||||
Twig default block
|
||||
==================
|
||||
|
||||
This part should be documented.
|
||||
|
244
docs/source/development/exports.rst
Normal file
244
docs/source/development/exports.rst
Normal file
@@ -0,0 +1,244 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Exports
|
||||
*******
|
||||
|
||||
Export is an important issue for the Chill software : users should be able to :
|
||||
|
||||
- compute statistics about their activity ;
|
||||
- list "things" which make part of their activities.
|
||||
|
||||
The `main bundle`_ provides a powerful framework to build custom queries with re-usable parts across differents bundles.
|
||||
|
||||
.. contents:: Table of content
|
||||
:local:
|
||||
|
||||
.. seealso::
|
||||
|
||||
`The issue where this framework was discussed <https://git.framasoft.org/Chill-project/Chill-Main/issues/9>`_
|
||||
Provides some information about the pursued features and architecture.
|
||||
|
||||
Concepts
|
||||
========
|
||||
|
||||
|
||||
Some vocabulary: 3 "Export elements"
|
||||
------------------------------------
|
||||
|
||||
Four terms are used for this framework :
|
||||
|
||||
exports
|
||||
provides some basic operation on the date. Two kind of exports are available :
|
||||
|
||||
- computed data : it may be "the number of people", "the number of activities", "the duration of activities", ...
|
||||
- list data : it may be "the list of people", "the list of activity", ...
|
||||
|
||||
filters
|
||||
The filters make a filter on the date: it removes some information the user doesn't want to introduce in the computation done by export. In other word, filters make a filter...
|
||||
|
||||
Example of filter: "people under 18 years olds", "activities between the 1st of June and the 31st December", ...
|
||||
|
||||
aggregators
|
||||
The aggregator aggregates the data into some group (some software use the term 'bucket').
|
||||
|
||||
Example of aggregator : "group people by gender", "group people by nationality", "group activity by type", ...
|
||||
|
||||
formatters
|
||||
The formatters format the data into a :class:`Symfony\Component\HttpFoundation\Response`, which will be returned "as is" by the controller to the web client.
|
||||
|
||||
Example of formatter: "format data as CSV", "format data as ods spreadsheet", ...
|
||||
|
||||
Anatomy of an export
|
||||
---------------------
|
||||
|
||||
An export may be explained as a sentence, where each part of this sentence refers to one or multiple exports element. Examples :
|
||||
|
||||
**Example 1**: Count the number of people having at least one activity in the last 12 month, and group them by nationality and gender, and format them in a CSV spreadsheet.
|
||||
|
||||
Here :
|
||||
|
||||
- *count the number of people* is the export part
|
||||
- *having at least one activity* is the filter part
|
||||
- *group them by nationality* is the aggregator part
|
||||
- *group them by gender* is a second aggregator part
|
||||
- *format the date in a CSV spreadsheet* is the formatter part
|
||||
|
||||
Note that :
|
||||
|
||||
- aggregators, filters, exports and aggregators are cross-bundle. Here the bundle *activity* provides a filter which apply on an export provided by the person bundle ;
|
||||
- there may exists multiple aggregator or filter for one export. Currently, only one export is allowed.
|
||||
|
||||
The result might be :
|
||||
|
||||
+-----------------------+----------------+---------------------------+
|
||||
| Nationality | Gender | Number of people |
|
||||
+=======================+================+===========================+
|
||||
| Russian | Male | 12 |
|
||||
+-----------------------+----------------+---------------------------+
|
||||
| Russian | Female | 24 |
|
||||
+-----------------------+----------------+---------------------------+
|
||||
| France | Male | 110 |
|
||||
+-----------------------+----------------+---------------------------+
|
||||
| France | Female | 150 |
|
||||
+-----------------------+----------------+---------------------------+
|
||||
|
||||
**Example 2**: Count the average duration of an activity with type "meeting", which occurs between the 1st of June and the 31st of December, group them by week, and format the data in a OpenDocument spreadsheet.
|
||||
|
||||
Here :
|
||||
|
||||
- *count the average duration of an activity* is the export part
|
||||
- *activity with type meeting* is a filter part
|
||||
- *activity which occurs between the 1st of June and the 31st of December* is a filter
|
||||
- *group them by week* is the aggregator part
|
||||
- *format the date in an OpenDocument spreadsheet* is the formatter part
|
||||
|
||||
The result might be :
|
||||
|
||||
+-----------------------+----------------------+
|
||||
| Week | Number of activities |
|
||||
+=======================+======================+
|
||||
| 2015-10 | 10 |
|
||||
+-----------------------+----------------------+
|
||||
| 2015-11 | 12 |
|
||||
+-----------------------+----------------------+
|
||||
| 2015-12 | 10 |
|
||||
+-----------------------+----------------------+
|
||||
| 2015-13 | 9 |
|
||||
+-----------------------+----------------------+
|
||||
|
||||
Authorization and exports
|
||||
-------------------------
|
||||
|
||||
Exports, filters and aggregators should not make see data the user is not allowed to see.
|
||||
|
||||
In other words, developers are required to take care of user authorization for each export.
|
||||
|
||||
It should exists a special role that should be granted to users which are allowed to build exports. For more simplicity, this role should apply on center, and should not requires special circles.
|
||||
|
||||
How does the magic works ?
|
||||
===========================
|
||||
|
||||
To build an export, we rely on the capacity of the database to execute queries with aggregate (i.e. GROUP BY) and filter (i.e. WHERE) instructions.
|
||||
|
||||
An export is an SQL query which is initiated by an export, and modified by aggregators and filters.
|
||||
|
||||
.. note::
|
||||
|
||||
**Example**: Count the number of people having at least one activity in the last 12 month, and group them by nationality and gender
|
||||
|
||||
1. The report initiate the query
|
||||
|
||||
.. code-block:: SQL
|
||||
|
||||
SELECT count(people.*) FROM people
|
||||
|
||||
2. The filter add a where and join clause :
|
||||
|
||||
.. code-block:: SQL
|
||||
|
||||
SELECT count(people.*) FROM people
|
||||
RIGHT JOIN activity
|
||||
WHERE activity.date IS BETWEEN now AND 6 month ago
|
||||
|
||||
3. The aggregator "nationality" add a GROUP BY clause and a column in the SELECT statement:
|
||||
|
||||
.. code-block:: sql
|
||||
|
||||
SELECT people.nationality, count(people.*) FROM people
|
||||
RIGHT JOIN activity
|
||||
WHERE activity.date IS BETWEEN now AND 6 month ago
|
||||
GROUP BY nationality
|
||||
|
||||
4. The aggregator "gender" do the same job as the nationality aggregator : it adds a GROUP BY clause and a column in the SELECT statement :
|
||||
|
||||
.. code-block:: sql
|
||||
|
||||
SELECT people.nationality, people.gender, count(people.*)
|
||||
FROM people RIGHT JOIN activity
|
||||
WHERE activity.date IS BETWEEN now AND 6 month ago
|
||||
GROUP BY nationality, gender
|
||||
|
||||
Each filter, aggregator and filter may collect parameters from the user by providing a form. This form is appended to the export form. Here is an example.
|
||||
|
||||
.. figure:: /_static/screenshots/development/export_form-fullpage.png
|
||||
|
||||
The screenshot show the export form for ``CountPeople`` (Nombre de personnes). The filter by date of birth is checked (*Filtrer par date de naissance de la personne*), which allow to show a subform, which is provided by the :class:`Chill\PersonBundle\Export\Filter\BirthdateFilter`. The other filter, which are unchecked, does not show the subform.
|
||||
|
||||
Two aggregators are also checked : by Country of birth (*Aggréger les personnes par pays de naissance*, corresponding class is :class:`Chill\PersonBundle\Export\Aggregator\CountryOfBirthAggregator`, which also open a subform. The aggregator by gender (*Aggréger les personnes par genre*) is also checked, but there is no corresponding subform.
|
||||
|
||||
The Export Manager
|
||||
------------------
|
||||
|
||||
The Export manager (:class:`Chill\MainBundle\Export\ExportManager` is the central class which register all exports, aggregators, filters and formatters.
|
||||
|
||||
The export manager is also responsible for orchestrating the whole export process, producing a :class:`Symfony\FrameworkBundle\HttpFoundation\Request` to each export request.
|
||||
|
||||
|
||||
The export form step
|
||||
--------------------
|
||||
|
||||
The form step allow to build a form, aggregating different parts of the module.
|
||||
|
||||
The building of forms is separated between different subform, which are responsible for rendering their part of the form (aggregators, filters, and export).
|
||||
|
||||
.. figure:: /_static/puml/exports/form_steps.png
|
||||
:scale: 40%
|
||||
|
||||
The formatter form step
|
||||
-----------------------
|
||||
|
||||
The formatter form is processed *after* the user filled the export form. It is built the same way, but receive in parameters the data entered by the user on the previous step (i.e. export form). It may then adapt it accordingly (example: show a list of columns selected in aggregators).
|
||||
|
||||
Processing the export
|
||||
---------------------
|
||||
|
||||
The export process may be explained by this schema :
|
||||
|
||||
.. figure:: /_static/puml/exports/processing_export.png
|
||||
:scale: 40%
|
||||
|
||||
(Click to enlarge)
|
||||
|
||||
|
||||
Export, formatters and filters explained
|
||||
========================================
|
||||
|
||||
Exports
|
||||
-------
|
||||
|
||||
This is an example of the ``CountPerson`` export :
|
||||
|
||||
.. literalinclude:: /_static/code/exports/CountPerson.php
|
||||
:language: php
|
||||
:linenos:
|
||||
|
||||
* **Line 36**: the ``getType`` function return a string. This string will be used to find the aggregtors and filters which will apply to this export.
|
||||
* **Line 41**: a simple description to help user to understand what your export does.
|
||||
* **Line 46**: The title of the export. A summary of what your export does.
|
||||
* **Line 51**: The list of roles requires to execute this export.
|
||||
* **Line 56**: We initiate the query here...
|
||||
* **Line 59**: We have to filter the query with centers the users checked in the form. We process the $acl variable to get all ``Center`` object in one array
|
||||
* **Line 63**: We create the query, with a query builder.
|
||||
* **Line 74**: We simply returns the result, but take care of hydrating the results as an array.
|
||||
* **Line 103**: return the list of formatters types which are allowed to apply on this filter
|
||||
|
||||
Filters
|
||||
-------
|
||||
|
||||
This is an example of the *filter by birthdate*. This filter ask some information in a form (`buildForm` is not empty), and this form must be validated. To performs this validations, we implement a new Interface: :class:`Chill\MainBundle\Export\ExportElementValidatedInterface`:
|
||||
|
||||
.. literalinclude:: /_static/code/exports/BirthdateFilter.php
|
||||
:language: php
|
||||
|
||||
.. todo::
|
||||
|
||||
Continue to explain the export framework
|
||||
|
||||
.. _main bundle: https://git.framasoft.org/Chill-project/Chill-Main
|
42
docs/source/development/forms.rst
Normal file
42
docs/source/development/forms.rst
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _forms:
|
||||
|
||||
Forms and form types
|
||||
####################
|
||||
|
||||
Date picker
|
||||
***********
|
||||
|
||||
Class
|
||||
:class:`Chill\MainBundle\Form\Type\ChillDateType`
|
||||
Extend
|
||||
:class:`Symfony\Component\Form\Extension\Core\Type\DateType`
|
||||
|
||||
|
||||
Usage :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
use Chill\MainBundle\Form\Type\ChillDateType;
|
||||
|
||||
$builder->add('date' ChillDateType::class);
|
||||
|
||||
Text editor
|
||||
***********
|
||||
|
||||
Add a text editor (by default).
|
||||
|
||||
Class
|
||||
:class:`Chill\MainBundle\Form\Type\ChillTextareaType`
|
||||
Options
|
||||
* :code:`disable_editor` to disable text editor
|
||||
|
||||
|
52
docs/source/development/index.rst
Normal file
52
docs/source/development/index.rst
Normal file
@@ -0,0 +1,52 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Development
|
||||
###########
|
||||
|
||||
As Chill rely on the `symfony <http://symfony.com>`_ framework, reading the framework's documentation should answer most of your questions. We are explaining here some tips to work with Chill, and things we provide to encounter our needs.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
Install Chill for development <installation.rst>
|
||||
Instructions to create a new bundle <create-a-new-bundle.rst>
|
||||
CRUD (Create - Update - Delete) for one entity <crud.rst>
|
||||
Routing <routing.rst>
|
||||
Menus <menus.rst>
|
||||
Forms <forms.rst>
|
||||
Access control model <access_control_model.rst>
|
||||
Messages to users <messages-to-users.rst>
|
||||
Pagination <pagination.rst>
|
||||
Localisation <localisation.rst>
|
||||
Logging <logging.rst>
|
||||
Database migrations <migrations.rst>
|
||||
Searching <searching.rst>
|
||||
Timelines <timelines.rst>
|
||||
Exports <exports.rst>
|
||||
Testing <make-test-working.rst>
|
||||
Useful snippets <useful-snippets.rst>
|
||||
manual/index.rst
|
||||
Assets <assets.rst>
|
||||
|
||||
Layout and UI
|
||||
**************
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
Layout / Template usage <user-interface/layout-template-usage.rst>
|
||||
Classes and mixins <user-interface/css-classes.rst>
|
||||
Widgets <user-interface/widgets.rst>
|
||||
Javascript function <user-interface/js-functions.rst>
|
||||
|
||||
|
||||
Help, I am lost !
|
||||
*****************
|
||||
|
||||
Write an email at info@champs-libres.coop, and we will help you !
|
155
docs/source/development/installation.rst
Normal file
155
docs/source/development/installation.rst
Normal file
@@ -0,0 +1,155 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _installation-for-development :
|
||||
|
||||
Installation for development
|
||||
****************************
|
||||
|
||||
Installation for development should allow:
|
||||
|
||||
- access to the source code,
|
||||
- upload the code to our CVS (i.e. `git`_) and
|
||||
- work with `composer`_.
|
||||
|
||||
As Chill is divided into bundles (the Symfony name for 'modules'), each bundle has his own repository.
|
||||
|
||||
Installation and big picture
|
||||
----------------------------
|
||||
|
||||
First, you should install Chill as described in the :ref:`basic-installation` section.
|
||||
|
||||
Two things must be modified :
|
||||
|
||||
First, add the `--prefer-source` argument when you create project.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
composer create-project chill-project/standard path/to/your/directory --stability=dev --prefer-source
|
||||
|
||||
Second, when composer ask you the following question : ::
|
||||
|
||||
Do you want to remove the existing VCS (.git, .svn..) history? [Y,n]?
|
||||
|
||||
**You should answer `n` (no).**
|
||||
|
||||
Once Chill is installed, all the downloaded bundles will be stored in the `/vendor` directories.
|
||||
In those directories, you will have access to the git commands.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd vendor/chill-project/main/
|
||||
$ git remote -v
|
||||
composer git://github.com/Chill-project/Standard.git (fetch)
|
||||
composer git://github.com/Chill-project/Standard.git (push)
|
||||
origin git://github.com/Chill-project/Standard.git (fetch)
|
||||
origin git@github.com:Chill-project/Standard.git (push)
|
||||
|
||||
Files cleaning after installation
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Composer will delete unrequired files, and add some. This is perfectly normal and will appears in your git index.
|
||||
But you should NOT delete those files.
|
||||
|
||||
This is the expected 'git status' result:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$git status
|
||||
#(...)
|
||||
|
||||
Modifications qui ne seront pas validées :
|
||||
(utilisez "git add/rm <fichier>..." pour mettre à jour ce qui sera validé)
|
||||
(utilisez "git checkout -- <fichier>..." pour annuler les modifications dans la copie de travail)
|
||||
|
||||
modifié: app/SymfonyRequirements.php
|
||||
supprimé: app/SymfonyStandard/Composer.php
|
||||
supprimé: app/SymfonyStandard/RootPackageInstallSubscriber.php
|
||||
modifié: app/check.php
|
||||
|
||||
You can ignore the local changes using the `git update-index --assume-unchanged` command.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ git update-index --assume-unchanged app/check.php
|
||||
$ git update-index --assume-unchanged app/SymfonyRequirements.php
|
||||
$ git update-index --assume-unchanged app/SymfonyStandard/Composer.php
|
||||
$ git update-index --assume-unchanged app/SymfonyStandard/RootPackageInstallSuscriber.php
|
||||
|
||||
Working with your own fork
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Ideally, you will work on a fork of the main github repository.
|
||||
To ensure that composer will download the code from **your** repository, you will have to adapt the `composer.json` file accordingly, using your own repositories.
|
||||
|
||||
For each Chill module that you have forked, add an indexed array into the "repositories" key of the composer.json file
|
||||
at the root of the chill installation directory if you want to force composer to download from your own forked repositories:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
"repositories": [
|
||||
{
|
||||
"type": "git",
|
||||
"url": "git://github.com/your-github-username/ChillMain.git"
|
||||
},
|
||||
{
|
||||
"type": "git",
|
||||
"url": "git://github.com/your-github-username/Chill-Person.git"
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
Then run composer update to load your forked code.
|
||||
If it does not happen, delete the content of the chill/vendor/chill-project/my_forked_bundle and relaunch composer update and the code will be downloaded from your fork.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
composer update
|
||||
|
||||
You may also `use aliases <https://getcomposer.org/doc/articles/aliases.md>`_ to define versions.
|
||||
|
||||
.. _editing-code-and-commiting :
|
||||
|
||||
Editing the code and commiting
|
||||
------------------------------
|
||||
|
||||
You may edit code in the `vendor/path/to/the/bundle` directory.
|
||||
|
||||
Once satisfied with your changes, you should commit as usually :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd vendor/path/to/bundle
|
||||
$ git status
|
||||
Sur la branche master
|
||||
Votre branche est à jour avec 'origin/master'.
|
||||
|
||||
rien à valider, la copie de travail est propre
|
||||
|
||||
.. warning
|
||||
|
||||
The git command must be run from you vendor bundle's path (`vendor/path/to/bundle`).
|
||||
|
||||
Tips
|
||||
^^^^
|
||||
|
||||
The command `composer status` (`see composer documentation <https://getcomposer.org/doc/03-cli.md#status>`_) will give you and idea of which bundle has been edited :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ cd ./../../ #back to the root project directory
|
||||
$ composer status
|
||||
You have changes in the following dependencies:
|
||||
/path/to/your/project/install/vendor/chill-project/main
|
||||
Use --verbose (-v) to see modified files
|
||||
|
||||
|
||||
|
||||
|
||||
.. _git: http://git-scm.org
|
||||
.. _composer: https://getcomposer.org
|
49
docs/source/development/localisation.rst
Normal file
49
docs/source/development/localisation.rst
Normal file
@@ -0,0 +1,49 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Localisation
|
||||
*************
|
||||
|
||||
Language in url
|
||||
===============
|
||||
|
||||
Language should be present in URL, conventionnaly as first argument.
|
||||
|
||||
.. code-block:: none
|
||||
|
||||
/fr/your/url/here
|
||||
|
||||
This allow users to change from one language to another one on each page, which may be useful in multilanguages teams. If the installation is single-language, the language switcher will not appears.
|
||||
|
||||
This is an example of routing defined in yaml :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_person_general_edit:
|
||||
pattern: /{_locale}/person/{person_id}/general/edit
|
||||
defaults: {_controller: ChillPersonBundle:Person:edit }
|
||||
|
||||
|
||||
Date and time
|
||||
==============
|
||||
|
||||
The `Intl extension <http://twig.sensiolabs.org/doc/extensions/intl.html>`_ is enabled on the Chill application.
|
||||
|
||||
You may format date and time using the `localizeddate` function :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
date|localizeddate('long', 'none')
|
||||
|
||||
By default, we prefer using the `long` format for date formatting.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Documentation for Intl Extension <http://twig.sensiolabs.org/doc/extensions/intl.html>`_
|
||||
Read the complete doc for the Intl extension.
|
||||
|
50
docs/source/development/logging.rst
Normal file
50
docs/source/development/logging.rst
Normal file
@@ -0,0 +1,50 @@
|
||||
.. Copyright (C) 2016 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Logging
|
||||
*******
|
||||
|
||||
.. seealso::
|
||||
|
||||
Symfony documentation: `How to user Monolog to write logs <http://symfony.com/doc/current/cookbook/logging/monolog.html>`_
|
||||
The symfony cookbook page about logging.
|
||||
|
||||
|
||||
A channel for custom logging has been created to store sensitive data.
|
||||
|
||||
The channel is named ``chill``.
|
||||
|
||||
The installer of chill should be aware that this channel may contains sensitive data and encrypted during backup.
|
||||
|
||||
Logging to channel `chill`
|
||||
============================
|
||||
|
||||
You should use the service named ``chill.main.logger``, as this :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$logger = $this->get('chill.main.logger');
|
||||
|
||||
You should store data into context, not in the log himself, which should remains the same for the action.
|
||||
|
||||
Example of usage :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
$logger->info("An action has been performed about a person", array(
|
||||
'person_lastname' => $person->getLastName(),
|
||||
'person_firstname' => $person->getFirstName(),
|
||||
'person_id' => $person->getId(),
|
||||
'by_user' => $user->getUsername()
|
||||
));
|
||||
|
||||
For further processing, it is a good idea to separate all fields (like firstname, lastname, ...) into different context keys.
|
||||
|
||||
By convention, you should store the username of the user performing the action under the ``by_user`` key.
|
||||
|
231
docs/source/development/make-test-working.rst
Normal file
231
docs/source/development/make-test-working.rst
Normal file
@@ -0,0 +1,231 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Make tests working
|
||||
******************
|
||||
|
||||
Unit and functional tests are important to ensure that bundle may be deployed securely.
|
||||
|
||||
In reason of the Chill architecture, test should be runnable from the bundle's directory and works correctly: this will allow continuous integration tools to run tests automatically.
|
||||
|
||||
.. note::
|
||||
|
||||
Integration tools (i.e. `travis-ci <https://travis-ci.org>`_) works like this :
|
||||
|
||||
* they clone the bundle repository in a virtual machine, using git
|
||||
* they optionnaly run `composer` to download and install depedencies
|
||||
* they optionnaly run other command to prepare a database, insert fixtures, ...
|
||||
* they run test
|
||||
|
||||
On the developer's machine test should be runnable with two or three commands **runned from the bundle directory** :
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ composer install --dev
|
||||
$ // command to insert fixtures, ...
|
||||
$ phpunit
|
||||
|
||||
This chapter has been inspired by `this useful blog post <http://blog.kevingomez.fr/2013/01/09/functional-testing-standalone-symfony2-bundles/>`_.
|
||||
|
||||
Bootstrap phpunit for a standalone bundle
|
||||
==========================================
|
||||
|
||||
Unit tests should run after achieving this step.
|
||||
|
||||
|
||||
phpunit.xml
|
||||
-----------
|
||||
|
||||
A `phpunit.xml.dist` file should be present at the bundle root.
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<phpunit bootstrap="./Tests/bootstrap.php" colors="true">
|
||||
<!-- the file "./Tests/boostrap.php" will be created on the next step -->
|
||||
<testsuites>
|
||||
<testsuite name="ChillMain test suite">
|
||||
<directory suffix="Test.php">./Tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<filter>
|
||||
<whitelist>
|
||||
<directory>./</directory>
|
||||
<exclude>
|
||||
<directory>./Resources</directory>
|
||||
<directory>./Tests</directory>
|
||||
<directory>./vendor</directory>
|
||||
</exclude>
|
||||
</whitelist>
|
||||
</filter>
|
||||
</phpunit>
|
||||
|
||||
|
||||
bootstrap.php
|
||||
--------------
|
||||
|
||||
A file `boostrap.php`, located in the `Tests` directory, will allow phpunit to resolve class autoloading :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
if (!is_file($autoloadFile = __DIR__.'/../vendor/autoload.php')) {
|
||||
throw new \LogicException('Could not find autoload.php in vendor/. Did you run "composer install --dev"?');
|
||||
}
|
||||
|
||||
require $autoloadFile;
|
||||
|
||||
|
||||
composer.json
|
||||
-------------
|
||||
|
||||
The `composer.json` file **located at the bundle's root** should contains all depencies needed to run test (and to execute bundle functions).
|
||||
|
||||
Ensure that all dependencies are included in the `require` and `require-dev` sections.
|
||||
|
||||
|
||||
Functional tests
|
||||
================
|
||||
|
||||
If you want to access services, database, and run functional tests, you will have to bootstrap a symfony app, with the minimal configuration. Three files are required :
|
||||
|
||||
* a `config_test.yml` file (eventually with a `config.yml`);
|
||||
* a `routing.yml` file
|
||||
* an `AppKernel.php` file
|
||||
|
||||
Adapt phpunit.xml
|
||||
-----------------
|
||||
|
||||
You should add reference to the new application within `phpunit.xml.dist`. The directive `<php>` should be added like this, if your `AppKernel.php` file is located in `Tests/Fixtures/App` directory:
|
||||
|
||||
.. code-block:: xml
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<phpunit bootstrap="./Tests/bootstrap.php" colors="true">
|
||||
<testsuites>
|
||||
<testsuite name="ChillMain test suite">
|
||||
<directory suffix="Test.php">./Tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<filter>
|
||||
<whitelist>
|
||||
<directory>./</directory>
|
||||
<exclude>
|
||||
<directory>./Resources</directory>
|
||||
<directory>./Tests</directory>
|
||||
<directory>./vendor</directory>
|
||||
</exclude>
|
||||
</whitelist>
|
||||
</filter>
|
||||
<!-- the lines we added -->
|
||||
<php>
|
||||
<server name="KERNEL_DIR" value="./Tests/Fixtures/App/" />
|
||||
</php>
|
||||
</phpunit>
|
||||
|
||||
AppKernel.php
|
||||
-------------
|
||||
|
||||
This file boostrap the app. It contains three functions. This is the file used in the ChillMain bundle :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
<?php
|
||||
|
||||
use Symfony\Component\HttpKernel\Kernel;
|
||||
use Symfony\Component\Config\Loader\LoaderInterface;
|
||||
|
||||
class AppKernel extends Kernel
|
||||
{
|
||||
public function registerBundles()
|
||||
{
|
||||
return array(
|
||||
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
|
||||
new Chill\MainBundle\ChillMainBundle(),
|
||||
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
|
||||
new Symfony\Bundle\TwigBundle\TwigBundle(),
|
||||
new \Symfony\Bundle\AsseticBundle\AsseticBundle(),
|
||||
#add here all the required bundle (some bundle are not required)
|
||||
);
|
||||
}
|
||||
|
||||
public function registerContainerConfiguration(LoaderInterface $loader)
|
||||
{
|
||||
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCacheDir()
|
||||
{
|
||||
return sys_get_temp_dir().'/ChillMainBundle/cache';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getLogDir()
|
||||
{
|
||||
return sys_get_temp_dir().'/ChillMainBundle/logs';
|
||||
}
|
||||
}
|
||||
|
||||
config_test.yml
|
||||
---------------
|
||||
|
||||
There are only few parameters required for the config file. This is a basic version for ChillMain :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# config/config_test.yml
|
||||
imports:
|
||||
- { resource: config.yml } #here we import a config.yml file, this is not required
|
||||
|
||||
framework:
|
||||
test: ~
|
||||
session:
|
||||
storage_id: session.storage.filesystem
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
# config/config.yml
|
||||
framework:
|
||||
secret: Not very secret
|
||||
router: { resource: "%kernel.root_dir%/config/routing.yml" }
|
||||
form: true
|
||||
csrf_protection: true
|
||||
session: ~
|
||||
default_locale: fr
|
||||
translator: { fallback: fr }
|
||||
profiler: { only_exceptions: false }
|
||||
templating: #required for assetic. Remove if not needed
|
||||
engines: ['twig']
|
||||
|
||||
.. note::
|
||||
|
||||
You must adapt config.yml file according to your required bundle. Some options will be missing, other may be removed...
|
||||
|
||||
.. note::
|
||||
|
||||
If you would like to tests different environments, with differents configuration, you could create differents config_XXX.yml files.
|
||||
|
||||
routing.yml
|
||||
------------
|
||||
|
||||
You should add there all routing information needed for your bundle.
|
||||
|
||||
.. code-block: yaml
|
||||
|
||||
chill_main_bundle:
|
||||
resource: "@CLChillMainBundle/Resources/config/routing.yml"
|
||||
|
||||
That's it. Tests should pass.
|
17
docs/source/development/manual/index.rst
Normal file
17
docs/source/development/manual/index.rst
Normal file
@@ -0,0 +1,17 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Developer manual
|
||||
*****************
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
routing-and-menus.rst
|
||||
|
||||
|
143
docs/source/development/manual/routing-and-menus.rst
Normal file
143
docs/source/development/manual/routing-and-menus.rst
Normal file
@@ -0,0 +1,143 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Routing and menus
|
||||
*****************
|
||||
|
||||
|
||||
The *Chill*'s architecture allows to choose bundle on each installation. This may lead to a huge diversity of installations, and a the developper challenge is to make his code working with all those possibles installations.
|
||||
|
||||
*Chill* uses menus to let users access easily to the most used functionalities. For instance, when you land on a "Person" page, you may access directly to his activities, notes, documents, ... in a single click on a side menu.
|
||||
|
||||
For a developer, it is easy to extend this menu with his own entries.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Symfony documentation about routing <http://symfony.com/doc/current/book/routing.html>`_
|
||||
This documentation should be read before diving into those lines
|
||||
|
||||
`Routes dans Chill <https://redmine.champs-libres.coop/issues/179>`_ (FR)
|
||||
The issue where we discussed routes. In French.
|
||||
|
||||
Create routes
|
||||
==============
|
||||
|
||||
.. note::
|
||||
|
||||
We recommand using `yaml` to define routes. We have not tested the existing other ways to create routes (annotations, ...). Help wanted.
|
||||
|
||||
The first step is as easy as create a route in symfony, and add some options in his description :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_main_dummy_0:
|
||||
pattern: /dummy/{personId}
|
||||
defaults: { _controller: CLChillMainBundle:Default:index }
|
||||
options:
|
||||
#we begin menu information here :
|
||||
menus:
|
||||
foo: #must appears in menu named 'foo'
|
||||
order: 500 #the order will be '500'
|
||||
label: foolabel #the label shown on menu. Will be translated
|
||||
otherkey: othervalue #you may add other informations, as needed by your layout
|
||||
bar: #must also appears in menu named 'bar'
|
||||
order: 500
|
||||
label: barlabel
|
||||
|
||||
The mandatory parameters under the `menus` definition are :
|
||||
|
||||
* `name`: the menu's name, defined as an key for the following entries
|
||||
* `order`. Note: if we have duplicate order's values, the order will be incremented. We recommand using big intervals within orders and publishing the orders in your documentation
|
||||
* `label`: the text which will be rendered inside the `<a>` tag. The label should be processed trough the `trans` filter (`{{ route.label|trans }}`)
|
||||
|
||||
You *may* also add other keys, which will be used optionally in the way the menu is rendered. See
|
||||
|
||||
.. warning::
|
||||
|
||||
Although all keys will be kept from your `yaml` definition to your menu template, we recommend not using those keys, which are reserved for a future implementations of Chill :
|
||||
|
||||
* `helper`, a text to help user or add more informations to him
|
||||
* `access` : which will run a test with `Expression Langage <http://symfony.com/doc/current/components/expression_language/index.html>`_ to determine if the user has the ACL to show the menu entry ;
|
||||
* `condition`, which will test with the menu context if the entry must appears
|
||||
|
||||
Show menu in twig templates
|
||||
===========================
|
||||
|
||||
To show our previous menu in the twig template, we invoke the `chill_menu` function. This will render the `foo` menu :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ chill_menu('foo') }}
|
||||
|
||||
Passing variables
|
||||
^^^^^^^^^^^^^^^^^
|
||||
|
||||
If your routes need arguments, i.e. an entity id, you should pass the as argument to the chill_menu function. If your route's pattern is `/person/{personId}`, your code become :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ chill_menu('foo', { 'args' : { 'personId' : person.id } } ) }}
|
||||
|
||||
Of course, `person` is a variable you must define in your code, which should have an `id` accessible property (i.e. : `$person->getId()`).
|
||||
|
||||
.. note::
|
||||
|
||||
Be aware that your arguments will be passed to all routes in a menu. If a route does not require `personId` in his pattern, the route will become `/pattern?personId=XYZ`. This should not cause problem in your application.
|
||||
|
||||
.. warning::
|
||||
|
||||
It is a good idea to reuse the same parameter's name in your pattern, to avoid collision. Prefer `/person/{personId}` to `/person/{id}`.
|
||||
|
||||
If you don't do that and another developer create a bundle with `person/{personId}/{id}` where `{id}` is the key for something else, this will cause a lot of trouble...
|
||||
|
||||
Rendering active entry
|
||||
^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Now, you want to render differently the *active* route of the menu [#f1]_. You should, in your controller or template, add the active route in your menu :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ chill_menu('foo', { 'activeRouteKey' : 'chill_main_dummy_0' } ) }}
|
||||
|
||||
On menu creation, the route wich has the key `chill_main_dummy_0` will be rendered on a different manner.
|
||||
|
||||
Define your own template
|
||||
-------------------------
|
||||
|
||||
By default, the menu is rendered with the default template, which is a simple `ul` list. You may create your own templates :
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
#MyBundle/Resources/views/Menu/MyMenu.html.twig
|
||||
<ul class="myMenu">
|
||||
{% for route in routes %}
|
||||
<li><a href="{{ path(route.key, args ) }}" class="{%- if activeRouteKey == route.key -%}active{%- endif -%}">{{ route.label|trans }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
Arguments available in your template :
|
||||
|
||||
* The `args` value are the value passed in the 'args' arguments requested by the `chill_menu` function.
|
||||
* `activeRouteKey` is the key of the currently active route.
|
||||
* `routes` is an array of routes. The array has this structure: `routes[order] = { 'key' : 'the_route_key', 'label' : 'the route label' }` The order is *resolved*: in case of collision (two routes from different bundles having the same order), the order will be incremented. You may find in the array your own keys (`{ 'otherkey' : 'othervalue'}` in the example above).
|
||||
|
||||
Then, you will call your own template with the `layout` argument :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ chill_menu('foo', { 'layout' : 'MyBundle:Menu:MyMenu.html.twig' } ) }}
|
||||
|
||||
.. note::
|
||||
|
||||
Take care of specifying the absolute path to layout in the function.
|
||||
|
||||
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
.. [#f1] In the default template, the currently active entry will be rendered with an "active" class : `<li class="active"> ... </li>`
|
123
docs/source/development/menus.rst
Normal file
123
docs/source/development/menus.rst
Normal file
@@ -0,0 +1,123 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
.. _menus :
|
||||
|
||||
Menus
|
||||
*****
|
||||
|
||||
Chill has created his own menu system
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Routes dans Chill [specification] <https://redmine.champs-libres.coop/issues/179>`_
|
||||
The issue wich discussed the implementation of routes.
|
||||
|
||||
Concepts
|
||||
========
|
||||
|
||||
.. warning::
|
||||
|
||||
to be written
|
||||
|
||||
|
||||
|
||||
Add a menu in a template
|
||||
========================
|
||||
|
||||
In your twig template, use the `chill_menu` function :
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{{ chill_menu('person', {
|
||||
'layout': 'ChillPersonBundle::menu.html.twig',
|
||||
'args' : {'id': person.id },
|
||||
'activeRouteKey': 'chill_person_view'
|
||||
}) }}
|
||||
|
||||
The available arguments are:
|
||||
|
||||
* `layout` : a custom layout. Default to `ChillMainBundle:Menu:defaultMenu.html.twig`
|
||||
* `args` : those arguments will be passed through the url generator.
|
||||
* `activeRouteKey` must be the route key name.
|
||||
|
||||
.. note::
|
||||
|
||||
The argument `activeRouteKey` may be a twig variable, defined elsewhere in your template, even in child templates.
|
||||
|
||||
|
||||
|
||||
Create an entry in an existing menu
|
||||
===================================
|
||||
|
||||
If a route belongs to a menu, you simply add this to his definition in routing.yml :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_person_history_list:
|
||||
pattern: /person/{person_id}/history
|
||||
defaults: { _controller: ChillPersonBundle:History:list }
|
||||
options:
|
||||
#declare menus
|
||||
menus:
|
||||
# the route should be in 'person' menu :
|
||||
person:
|
||||
#and have those arguments :
|
||||
order: 100
|
||||
label: menu.person.history
|
||||
|
||||
* `order` (mandatory) : the order in the menu. It is preferrable to increment by far more than 1.
|
||||
* `label` (mandatory) : a translatable string.
|
||||
* `helper` (optional) : a text to help people to understand what does the menu do. Not used in default implementation.
|
||||
* `condition` (optional) : an `Expression Language <http://symfony.com/doc/current/components/expression_language/index.html> `_ which will make the menu appears or not. Typically, it may be used to say "show this menu only if the person concerned is more than 18". **Not implemented yet**.
|
||||
* `access` (optional) : an Expression Language to evalute the possibility, for the user, to show this menu according to Access Control Model. **Not implemented yet.**
|
||||
|
||||
You may add additional keys, but should not use the keys described above.
|
||||
|
||||
You may add the same route to multiple menus :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_person_history_list:
|
||||
pattern: /person/{person_id}/history
|
||||
defaults: { _controller: ChillPersonBundle:History:list }
|
||||
options:
|
||||
menus:
|
||||
menu1:
|
||||
order: 100
|
||||
label: menu.person.history
|
||||
menu2:
|
||||
order: 100
|
||||
label: another.label
|
||||
|
||||
|
||||
|
||||
Customize menu rendering
|
||||
========================
|
||||
|
||||
You may customize menu rendering by using the `layout` option.
|
||||
|
||||
.. warning ::
|
||||
|
||||
TODO : this part should be written.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.. _caveats :
|
||||
|
||||
Caveats
|
||||
=======
|
||||
|
||||
Currently, you may pass arguments globally to each menu, and they will be all passed to route url. This means that :
|
||||
|
||||
* the argument name in the route entry must match the argument key in menu declaration in twig template
|
||||
* if an argument is missing to generate an url, the url generator will throw a `Symfony\Component\Routing\Exception\MissingMandatoryParametersException`
|
||||
* if the argument name is not declared in route entry, it will be added to the url, (example: `/my/route?additional=foo`)
|
129
docs/source/development/messages-to-users.rst
Normal file
129
docs/source/development/messages-to-users.rst
Normal file
@@ -0,0 +1,129 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Messages to users, flashbags and buttons
|
||||
****************************************
|
||||
|
||||
|
||||
.. _flashbags :
|
||||
|
||||
Flashbags
|
||||
==========
|
||||
|
||||
The four following levels are defined :
|
||||
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|Key |Intent |
|
||||
+===========+==============================================================================================+
|
||||
|alert |A message not linked with the user action, but which should require an action or a |
|
||||
| |correction. |
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|success |The user action succeeds. |
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|notice |A simple message to give information to the user. The message may be linked or not linked with|
|
||||
| |the user action. |
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|warning |A message linked with an action, the user should correct. |
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|error |The user's action failed: he must correct something to process the action. |
|
||||
+-----------+----------------------------------------------------------------------------------------------+
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Flash Messages on Symfony documentation <http://symfony.com/doc/current/book/controller.html#flash-messages>`_
|
||||
Learn how to use flash messages in controller.
|
||||
|
||||
|
||||
Buttons
|
||||
========
|
||||
|
||||
Some actions are available to decorate ``a`` links and ``buttons``.
|
||||
|
||||
To add the action on button, use them as class along with ``sc-button`` :
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<a class="sc-button bt-create">Create an entity</a>
|
||||
|
||||
<button class="sc-button bt-submit" type="submit">Submit</button>
|
||||
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Action | Class | Description |
|
||||
+===========+================+==============================================================================+
|
||||
| Submit | ``bt-submit`` | Submit a form. Use only if action is not "save". |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Create | ``bt-create`` | - Link to a form to create an entity (alias: ``bt-new``) |
|
||||
| | or ``bt-new`` | - Submitting this form will create a new entity |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Reset | ``bt-reset`` | Reset a form |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Delete | ``bt-delete`` | - Link to a form to delete an entity |
|
||||
| | | - Submitting this form will remove the entity |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Edit | ``bt-edit`` or | Link to a form to edit an entity |
|
||||
| | ``bt-update`` | |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Save | ``bt-save`` | Submitting this form will save change on the entity |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Action | ``bt-action`` | Generic link to an action |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
| Cancel | ``bt-cancel`` | Cancel an action and go back to another page |
|
||||
+-----------+----------------+------------------------------------------------------------------------------+
|
||||
|
||||
Styling buttons
|
||||
---------------
|
||||
|
||||
Small buttons, mainly to use inline
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<p><a class="sc-button bt-create bt-small">You button</a></p>
|
||||
|
||||
You can omit content and show a button with an icon only :
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<a class="sc-button bt-create"></a>
|
||||
|
||||
You can hide content and show it only on hover
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<a class="sc-button bt-create has-hidden"><span class="show-on-hover">Showed when mouse pass on</span></a>
|
||||
|
||||
You can customize the icon :
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<a class="sc-button bt-create change-icon"><i class="fa fa-icon"></i>Button with custom icon</a>
|
||||
|
||||
Grouping buttons
|
||||
----------------
|
||||
|
||||
Grouping buttons can be done using ``ul.record_actions`` element (an ``ul`` list with class ``record_actions``):
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<ul class="record_actions">
|
||||
|
||||
<li class="cancel">
|
||||
<a class="sc-button bt-cancel">Cancel</a>
|
||||
<li>
|
||||
|
||||
<li>
|
||||
<a class="sc-button bt-save">Save</a>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
The element with the ``cancel`` class will be set in first position.
|
||||
|
||||
Inside table, the space between elements will be shorter.
|
||||
|
||||
You can add the class ``record_actions_small`` if you want shorter space between elements.
|
||||
|
101
docs/source/development/migrations.rst
Normal file
101
docs/source/development/migrations.rst
Normal file
@@ -0,0 +1,101 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Database Migrations
|
||||
********************
|
||||
|
||||
Every bundle potentially brings his own database operations : to persist entities, developers have to create database schema, creating indexes,...
|
||||
|
||||
Those schema might be changed (the less is the better) from time to time.
|
||||
|
||||
Consequence: each bundle should bring his own migration files, which will bring the database consistent with the operation you will run in your code. They will be gathered into the app installation, ready to be executed by the chill's installer.
|
||||
|
||||
Currently, we use `doctrine migration`_ to manage those migration files. A `composer`_ script located in the **chill standard** component will copy the migrations from your bundle to the doctrne migration's excepted directory after each install and/or update operation.
|
||||
|
||||
.. seealso::
|
||||
|
||||
The `doctrine migration`_ documentation
|
||||
Learn concepts about migrations files and scripts and the doctrine ORM
|
||||
|
||||
The `doctrine migration bundle`_ documentation
|
||||
Learn about doctrine migration integration with Symfony framework
|
||||
|
||||
Shipping migration files
|
||||
========================
|
||||
|
||||
Migrations files should be shipped under the Resource/migrations directory. You could customize the migration directory by adding extra information in your composer.json:
|
||||
|
||||
.. code-block:: json
|
||||
|
||||
"extra": {
|
||||
"migration-source": "path/to/my/dir"
|
||||
}
|
||||
|
||||
The class namespace should be `Application\Migrations`, as expected by doctrine migration. Only the files which will be executed by doctrine migration will be moved: they must have the pattern `VersionYYYYMMDDHHMMSS.php` where YYYY is the year, MM the month, DD the day, HH the hour, MM the month and SS the second of creation.
|
||||
|
||||
They will be moved automatically by composer when you install or update a bundle.
|
||||
|
||||
Executing migration files
|
||||
==========================
|
||||
|
||||
The installers will have to execute migrations files manually, running
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
php app/console doctrine:migrations:status #will give the current status of the database
|
||||
php app/console doctrine:migrations:migrate #process the update
|
||||
|
||||
|
||||
Updating migration files
|
||||
=========================
|
||||
|
||||
.. warning::
|
||||
|
||||
After an installation, migration files will be executed and registered as executed in the database (the version timestamp is recorded into the :title:`migrations_versions` table). If you update your migration file code, the file will still be considered as "executed" by doctrine migration, which will not offers the possibility to run the migration again.
|
||||
|
||||
Consequently, updating migration file should only be considered during development phase, and not published on public git branches. If you want to edit your database schema, you should create a new migration file, with a new timestamp, which will proceed to your schema adaptations.
|
||||
|
||||
Every time a migration file is discovered, the composer'script will check if the migration exists in the local migration directory. If yes, the script will compare two file for changes (using a md5 hash). If migrations are discovered, the script will ask the installer to know if he must replace the file or ignore it.
|
||||
|
||||
.. note::
|
||||
|
||||
You can manually run composer script by launching `composer run-script post-update-cmd` from your root chill installation's directory.
|
||||
|
||||
|
||||
.. _doctrine migration: http://www.doctrine-project.org/projects/migrations.html
|
||||
.. _doctrine migration bundle : http://symfony.com/doc/master/bundles/DoctrineMigrationsBundle/index.html
|
||||
.. _composer : https://getcomposer.org
|
||||
|
||||
Tips for development
|
||||
====================
|
||||
|
||||
Migration and data
|
||||
------------------
|
||||
|
||||
Each time you create a migration script, you should ensure that it will not lead to data losing. Eventually, feel free to use intermediate steps.
|
||||
|
||||
Generation
|
||||
----------
|
||||
|
||||
You can generate migration file from the command line, using those commands:
|
||||
|
||||
* `php app/console doctrine:migrations:diff` to generate a migration file by comparing your current database to your mapping information
|
||||
* `php app/console doctrine:migrations:generate` to generate a blank migration file.
|
||||
|
||||
Those files will be located into `app/DoctrineMigrations` directory. You will have to copy those file to your the directory `Resources/migrations` into your bundle directory.
|
||||
|
||||
Comments and documentation
|
||||
--------------------------
|
||||
|
||||
As files are copied from your bundle to the `app/DoctrineMigrations` directory, the link between your bundle and the copied file will be unclear. Please add all relevant documentation which will allow future developers to make a link between your file and your bundle.
|
||||
|
||||
Inside the script
|
||||
-----------------
|
||||
|
||||
The script which move the migrations files to app directory `might be found here
|
||||
<https://github.com/Champs-Libres/ComposerBundleMigration/blob/master/Composer/Migrations.php>
|
189
docs/source/development/pagination.rst
Normal file
189
docs/source/development/pagination.rst
Normal file
@@ -0,0 +1,189 @@
|
||||
.. Copyright (C) 2016 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Pagination
|
||||
##########
|
||||
|
||||
The Bundle :code:`Chill\MainBundle` provides a **Pagination** api which allow you to easily divide results list on different pages.
|
||||
|
||||
A simple example
|
||||
****************
|
||||
|
||||
In the controller, get the :class:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance.
|
||||
|
||||
|
||||
.. literalinclude:: pagination/example.php
|
||||
:language: php
|
||||
|
||||
|
||||
Then, render the pagination using the dedicated twig function.
|
||||
|
||||
.. code-block:: html+twig
|
||||
|
||||
{% extends "ChillPersonBundle::layout.html.twig" %}
|
||||
|
||||
{% block title 'Item list'|trans %}
|
||||
|
||||
{% block personcontent %}
|
||||
|
||||
<table>
|
||||
|
||||
{# ... your items here... #}
|
||||
|
||||
</table>
|
||||
|
||||
{% if items|length < paginator.getTotalItems %}
|
||||
{{ chill_pagination(paginator) }}
|
||||
{% endif %}
|
||||
|
||||
|
||||
The function :code:`chill_pagination` will, by default, render a link to the 10 previous page (if they exists) and the 10 next pages (if they exists). Assuming that we are on page 5, the function will render a list to ::
|
||||
|
||||
Previous 1 2 3 4 **5** 6 7 8 9 10 11 12 13 14 Next
|
||||
|
||||
Understanding the magic
|
||||
=======================
|
||||
|
||||
Where does the :code:`$paginator` get the page number ?
|
||||
-------------------------------------------------------
|
||||
|
||||
Internally, the :code:`$paginator` object has a link to the :code:`Request` object, and it reads the :code:`page` parameter which contains the current page number. If this parameter is not present, the :code:`$paginator` assumes that we are on page 1.
|
||||
|
||||
.. figure:: /_static/puml/pagination-sequence.png
|
||||
|
||||
The :code:`$paginator` get the current page from the request.
|
||||
|
||||
Where does the :code:`$paginator` get the number of items per page ?
|
||||
--------------------------------------------------------------------
|
||||
|
||||
As above, the :code:`$paginator` can get the number of items per page from the :code:`Request`. If none is provided, this is given by the configuration which is, by default, 50 items per page.
|
||||
|
||||
:code:`PaginatorFactory`, :code:`Paginator` and :code:`Page`
|
||||
************************************************************
|
||||
|
||||
:code:`PaginatorFactory`
|
||||
========================
|
||||
|
||||
The :code:`PaginatorFactory` may create more than one :code:`Paginator` in a single action. Those :code:`Paginator` instance may redirect to different routes and/or routes parameters.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// create a paginator for the route 'my_route' with some parameters (arg1 and arg2)
|
||||
$paginatorMyRoute = $paginatorFactory->create($total, 'my_route', array('arg1' => 'foo', 'arg2' => $bar);
|
||||
|
||||
Those parameters will override the current parameters.
|
||||
|
||||
The :code:`PaginatorFactory` has also some useful shortcuts :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// get current page number
|
||||
$paginatorFactory->getCurrentPageNumber( )
|
||||
// get the number of items per page **for the current request**
|
||||
$paginatorFactory->getCurrentItemsPerPage( )
|
||||
// get the number of the first item **for the current page**
|
||||
$paginatorFactory->getCurrentPageFirstItemNumber( )
|
||||
|
||||
|
||||
Working with :code:`Paginator` and :code:`Page`
|
||||
===============================================
|
||||
|
||||
The paginator has some function to give the number of pages are required to displayed all the results, and give some information about the number of items per page :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// how many page count this paginator ?
|
||||
$paginator->countPages(); // return 20 in our example
|
||||
|
||||
// we may get the number of items per page
|
||||
$paginator->getItemsPerPage(); // return 20 in our example
|
||||
|
||||
A :code:`Paginator` instance create instance of :code:`Page`, each :code:`Page`, which is responsible for generating the URL to the page number it represents. Here are some possibilities using :code:`Page` and :code:`Paginator` :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// get the current page
|
||||
$page = $paginator->getCurrentPage();
|
||||
// on which page are we ?
|
||||
$page->getNumber(); // return 5 in this example (we are on page 5)
|
||||
// generate the url for page 5
|
||||
$page->generateUrl(); // return '/<your route here>?page=5
|
||||
// what is the first item number on this page ?
|
||||
$page->getFistItemNumber(); // return 101 in our example (20 items per page)
|
||||
// what is the last item number on this page ?
|
||||
$page->getLastItemNumber(); // return 120 in our example
|
||||
|
||||
// we can access directly the next and current page
|
||||
if ($paginator->hasNextPage()) {
|
||||
$next = $paginator->getNextPage();
|
||||
}
|
||||
if ($paginator->hasPreviousPage()) {
|
||||
$previous = $paginator->getPreviousPage();
|
||||
}
|
||||
|
||||
// we can access directly to a given page number
|
||||
if ($paginator->hasPage(10)) {
|
||||
$page10 = $paginator->getPage(10);
|
||||
}
|
||||
|
||||
// we can iterate over our pages through a generator
|
||||
foreach ($paginator->getPagesGenerator() as $page) {
|
||||
$page->getNumber();
|
||||
}
|
||||
|
||||
// check that a page object is the current page
|
||||
$paginator->isCurrentPage($page); // return false
|
||||
|
||||
.. warning::
|
||||
|
||||
When calling a page which does not exists, the :code:`Paginator` will throw a `RuntimeException`. Example :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// our last page is 10
|
||||
$paginator->getPage(99); // out of range => throw `RuntimeException`
|
||||
|
||||
// our current page is 1 (the first page)
|
||||
$paginator->getPreviousPage; // does not exists (the fist page is always 1) => throw `RuntimeException`
|
||||
|
||||
.. note::
|
||||
|
||||
When you create a :code:`Paginator` for the current route and route parameters, the :code:`Page` instances will keep the same parameters and routes :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
// assuming our route is 'my_route', for the pattern '/my/{foo}/route',
|
||||
// and the current route is '/my/value/route?arg2=bar'
|
||||
|
||||
// create a paginator for the current route and route parameters :
|
||||
$paginator = $paginatorFactory->create($total);
|
||||
|
||||
// get the next page
|
||||
if ($paginator->hasNext()) {
|
||||
$next = $paginator->getNextPage();
|
||||
|
||||
// get the route to the page
|
||||
$page->generateUrl(); // will print 'my/value/route?arg2=bar&page=2'
|
||||
}
|
||||
|
||||
|
||||
Having a look to the `full classes documentation may provide some useful information <http://api.chill.social/Chill-Main/master/namespace-Chill.MainBundle.Pagination.html>`_.
|
||||
|
||||
|
||||
Customizing the rendering of twig's :code:`chill_pagination`
|
||||
************************************************************
|
||||
|
||||
You can provide your own layout for rendering the pagination: provides your twig template as a second argument :
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{{ chill_pagination(paginator, 'MyBundle:Pagination:MyTemplate.html.twig') }}
|
||||
|
||||
The template will receive the :code:`$paginator` as :code:`paginator` variable. Let's have a look `at the current template <https://framagit.org/Chill-project/Chill-Main/blob/master/Resources/views/Pagination/long.html.twig>`_.
|
||||
|
42
docs/source/development/pagination/example.php
Normal file
42
docs/source/development/pagination/example.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MyBundle\Controller;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
|
||||
class ItemController extends Controller {
|
||||
|
||||
public function yourAction()
|
||||
{
|
||||
$em = $this->getDoctrine()->getManager();
|
||||
// first, get the number of total item are available
|
||||
$total = $em
|
||||
->createQuery("SELECT COUNT (item.id) FROM ChillMyBundle:Item item")
|
||||
->getSingleScalarResult();
|
||||
|
||||
// get the PaginatorFactory
|
||||
$paginatorFactory = $this->get('chill_main.paginator_factory');
|
||||
|
||||
// create a pagination instance. This instance is only valid for
|
||||
// the current route and parameters
|
||||
$paginator = $paginatorFactory->create($total);
|
||||
|
||||
// launch your query on item. Limit the query to the results
|
||||
// for the current page using the paginator
|
||||
$items = $em->createQuery("SELECT item FROM ChillMyBundle:Item item WHERE <your clause>")
|
||||
// use the paginator to get the first item number
|
||||
->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
|
||||
// use the paginator to get the number of items to display
|
||||
->setMaxResults($paginator->getItemsPerPage());
|
||||
|
||||
return $this->render('ChillMyBundle:Item:list.html.twig', array(
|
||||
'items' => $items,
|
||||
'paginator' => $paginator
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
68
docs/source/development/routing.rst
Normal file
68
docs/source/development/routing.rst
Normal file
@@ -0,0 +1,68 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Routing
|
||||
#######
|
||||
|
||||
Our goal is to ease the installation of the different bundle. Users should not have to dive into complicated config files to install bundles.
|
||||
|
||||
A routing loader available for all bundles
|
||||
===========================================
|
||||
|
||||
A Chill bundle may rely on the Routing Loader defined in ChillMain.
|
||||
|
||||
The loader will load `yml` or `xml` files. You simply have to add them into `chill_main` config
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
chill_main:
|
||||
# ... other stuff here
|
||||
routing:
|
||||
resources:
|
||||
- @ChillMyBundle/Resources/config/routing.yml
|
||||
|
||||
Load routes automatically
|
||||
-------------------------
|
||||
|
||||
But this force users to modify config files. To avoid this, you may prepend config implementing the `PrependExtensionInterface` in the `YourBundleExtension` class. This is an example from **chill main** bundle :
|
||||
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\MainBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
|
||||
class ChillMainExtension extends Extension implements PrependExtensionInterface
|
||||
{
|
||||
|
||||
public function load(array $configs, ContainerBuilder $container)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
public function prepend(ContainerBuilder $container)
|
||||
{
|
||||
|
||||
//add current route to chill main
|
||||
//this is where the resource is added automatically in the config
|
||||
$container->prependExtensionConfig('chill_main', array(
|
||||
'routing' => array(
|
||||
'resources' => array(
|
||||
'@ChillMainBundle/Resources/config/routing.yml'
|
||||
)
|
||||
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
276
docs/source/development/searching.rst
Normal file
276
docs/source/development/searching.rst
Normal file
@@ -0,0 +1,276 @@
|
||||
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Searching
|
||||
*********
|
||||
|
||||
Chill should provide information needed by users when they need it. Searching within bundle, entities,... is an important feature to achieve this goal.
|
||||
|
||||
The Main Bundle provide interfaces to ease the developer work. It will also attempt that search will work in the same way accross bundles.
|
||||
|
||||
.. contents:: Table of content
|
||||
:local:
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Our blog post about searching (in French) <http://blog.champs-libres.coop/vie-des-champs/2015/01/06/va-chercher-chill-la-recherche-dans-chill-logiciel-libre-service-social.html>`_
|
||||
This blog post give some information for end-users about searching.
|
||||
|
||||
`The issue about search behaviour <https://redmine.champs-libres.coop/issues/377>`_
|
||||
Where the search behaviour is defined.
|
||||
|
||||
Searching in a glance for developers
|
||||
====================================
|
||||
|
||||
Chill suggests to use an easy-to-learn language search.
|
||||
|
||||
.. note::
|
||||
|
||||
We are planning to provide a form to create automatically search pattern according to this language. Watch the `issue regarding this feature <https://redmine.champs-libres.coop/issues/389>`_.
|
||||
|
||||
The language is an association of search terms. Search terms may contains :
|
||||
|
||||
- **a domain**: this is "the domain you want to search" : it may some entities like people, reports, ... Example : `@person` to search accross people, `@report` to browse reports, ... The search pattern may have **a maximum of one** domain by search, providing more should throw an error, and trigger a warning for users.
|
||||
- **arguments and their values** : This is "what you search". Arguments narrow the search to specific fields : username, date of birth, nationality, ... The syntax is `argument:value`. I.e.: ` birthdate:2014-12-15`, `firstname:Depardieu`, ... **Arguments are optional**. If the value of an argument contains spaces or characters like punctuation, quotes ("), the value should be provided between parenthesis : `firstname:(Van de snoeck)`, `firstname:(M'bola)`, ...
|
||||
- **default value** : this the "rest" of the search, not linked with any arguments or domain. Example : `@person dep` (`dep` is the "default value"), or simply `dep` if any domain is provided (which is perfectly acceptable). If a string is not idenfied as argument or domain, it will be present in the "default" term.
|
||||
|
||||
If a search pattern (provided by the user) does not contains any domain, the search must be run across default domain/search modules.
|
||||
|
||||
A domain may be supported by different search modules. For instance, if you provide the domain `@person`, the end-user may receive results of exact firstname/lastname, but also result with spelling suggestion, ... **But** if results do not fit into the first page (if you have 75 results and the screen show only 50 results), the next page should contains only the results from the required module.
|
||||
|
||||
For instance : a user search across people by firstname/lastname, the exact spelling contains 10 results, the "spelling suggestion" results contains 75 names, but show only the first 50. If the user want to see the last 25, the next screen should not contains the results by firstname/lastname.
|
||||
|
||||
Allowed characters as arguments
|
||||
===============================
|
||||
|
||||
In order to execute regular expression, the allowed chararcters in arguments are a-z characters, numbers, and the sign '-'. Spaces and special characters like accents are note allowed (the accents are removed during parsing).
|
||||
|
||||
Special characters and uppercase
|
||||
================================
|
||||
|
||||
The search should not care about lowercase/uppercase and accentued characters. Currently, they are removed automatically by the `chill.main.search_provider`.
|
||||
|
||||
Implementing search module for dev
|
||||
===================================
|
||||
|
||||
To implement a search module, you should :
|
||||
|
||||
- create a class which implements the `Chill\MainBundle\Search\SearchInterface` class. An abstract class `Chill\MainBundle\Search\AbstractSearch` will provide useful assertions for parsing date string to `DateTime` objects, ...
|
||||
- register the class as a service, and tag the service with `chill.search` and an appropriate alias
|
||||
|
||||
The search logic is provided under the `/search` route.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`The implementation of a search module in Person bundle <https://github.com/Chill-project/Person/blob/master/Search/PersonSearch.php>`_
|
||||
An example of implementationhttps://github.com/Chill-project/Main/blob/master/DependencyInjection/SearchableServicesCompilerPass.php
|
||||
|
||||
.. note::
|
||||
|
||||
**Internals explained** : the services tagged with `chill.search` are gathered into the `chill.main.search_provider` service during compilation (`see the compiler pass <https://github.com/Chill-project/Main/blob/master/DependencyInjection/SearchableServicesCompilerPass.php>`_).
|
||||
|
||||
The `chill.main.search_provider` service allow to :
|
||||
|
||||
- retrieve all results (as html string) for all search module concerned by the search (according to the domain provided or modules marked as default)
|
||||
- retrieve result for one search module
|
||||
|
||||
The SearchInterface class
|
||||
-------------------------
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Search;
|
||||
|
||||
use Chill\MainBundle\Search\AbstractSearch;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Chill\PersonBundle\Entity\Person;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerAware;
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
|
||||
use Chill\MainBundle\Search\ParsingException;
|
||||
|
||||
class PersonSearch extends AbstractSearch
|
||||
{
|
||||
|
||||
// indicate which domain you support
|
||||
// you may respond TRUE to multiple domain, according to your logic
|
||||
public function supports($domain, $format='html')
|
||||
{
|
||||
return 'person' === $domain;
|
||||
}
|
||||
|
||||
// if your domain must be called when no domain is provided, should return true
|
||||
public function isActiveByDefault()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// if multiple module respond to the same domain, indicate an order for your search.
|
||||
public function getOrder()
|
||||
{
|
||||
return 100;
|
||||
}
|
||||
|
||||
|
||||
// This is where your search logic should be executed.
|
||||
// This method must return an HTML string (a string with HTML tags)
|
||||
// see below about the structure of the $term array
|
||||
public function renderResult(array $terms, $start = 0, $limit = 50, array $options = array(), $format = 'html')
|
||||
{
|
||||
return $this->container->get('templating')->render('ChillPersonBundle:Person:list.html.twig',
|
||||
array(
|
||||
// you should implements the `search` function somewhere :-)
|
||||
'persons' => $this->search($terms, $start, $limit, $options),
|
||||
// recomposePattern is available in AbstractSearch class
|
||||
'pattern' => $this->recomposePattern($terms, array('nationality',
|
||||
'firstname', 'lastname', 'birthdate', 'gender'), $terms['_domain']),
|
||||
// you should implement the `count` function somewhere :-)
|
||||
'total' => $this->count($terms)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Values for :code:`$options`
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
:code:`$options` is an array with the following keys:
|
||||
|
||||
- :code:`SearchInterface::SEARCH_PREVIEW_OPTION` (bool): if the current view is a preview (the first 5 results) or not ;
|
||||
- :code:`SearchInterface::REQUEST_QUERY_PARAMETERS` (bool): some parameters added to the query (under the key :code:`SearchInterface::REQUEST_QUERY_KEY_ADD_PARAMETERS`) and that can be interpreted. Used, for instance, when calling a result in json format when searching for interactive picker form.
|
||||
|
||||
|
||||
|
||||
|
||||
Structure of array `$term`
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The array term is parsed automatically by the `main.chill.search_provider` service.
|
||||
|
||||
.. note::
|
||||
If you need to parse a search pattern, you may use the function `parse($pattern)` provided by the service.
|
||||
|
||||
The array `$term` have the following structure after parsing :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
array(
|
||||
'_domain' => 'person', //the domain, without the '@'
|
||||
'argument1' => 'value', //the argument1, with his value
|
||||
'argument2' => 'my value with spaces', //the argument2
|
||||
'_default' => 'abcde ef' // the default term
|
||||
);
|
||||
|
||||
The original search would have been : `@person argument1:value argument2:(my value with spaces) abcde ef`
|
||||
|
||||
.. warning::
|
||||
The search values are always unaccented.
|
||||
|
||||
Returning a result in json
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The json format is mainly used by "select2" widgets.
|
||||
|
||||
When returning a result in json, the SearchInterface should only return an array with following keys:
|
||||
|
||||
- :code:`more` (bool): if the search has more result than the current page ;
|
||||
- :code:`results` (array): a list of result, where:
|
||||
|
||||
- :code:`text` (string): the text that should be displayed in browser ;
|
||||
- :code:`id` (string): the id of the entity.
|
||||
|
||||
|
||||
|
||||
Register the service
|
||||
--------------------
|
||||
|
||||
You should add your service in the configuration, and add a `chill.search` tag and an alias.
|
||||
|
||||
Example :
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
services:
|
||||
chill.person.search_person:
|
||||
class: Chill\PersonBundle\Search\PersonSearch
|
||||
#your logic here
|
||||
tags:
|
||||
- { name: chill.search, alias: 'person_regular' }
|
||||
|
||||
The alias will be used to get the results narrowed to this search module, in case of pagination (see above).
|
||||
|
||||
Parsing date
|
||||
============
|
||||
|
||||
The class `Chill\MainBundle\Search\AbstractSearch` provides a method to parse date :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
//from subclasses
|
||||
$date = $this->parseDate($string);
|
||||
|
||||
`$date` will be an instance of `DateTime <http://php.net/manual/en/class.datetime.php>`_.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`The possibility to add periods instead of date <https://redmine.champs-libres.coop/issues/390>`_
|
||||
Which may be a future improvement for search with date.
|
||||
|
||||
Exceptions
|
||||
==========
|
||||
|
||||
The logic of the search is handled by the controller for the `/search` path.
|
||||
|
||||
You should throw those Exception from your instance of `SearchInterface` if needed :
|
||||
|
||||
Chill\MainBundle\Search\ParsingException
|
||||
If the terms does not fit your search logic (for instance, conflicting terms)
|
||||
|
||||
Expected behaviour
|
||||
==================
|
||||
|
||||
Operators between multiple terms
|
||||
--------------------------------
|
||||
|
||||
Multiple terms should be considered are "AND" instructions :
|
||||
|
||||
@person nationality:RU firstname:dep
|
||||
the people having the Russian nationality AND having DEP in their name
|
||||
|
||||
@person birthdate:2015-12-12 charles
|
||||
the people having 'charles' in their name or firstname AND born on December 12 2015
|
||||
|
||||
Spaces in default
|
||||
-----------------
|
||||
|
||||
Spaces in default terms should be considered as "AND" instruction
|
||||
|
||||
@person charle dep
|
||||
people having "dep" AND "charles" in their firstname or lastname. Match "Charles Depardieu" but not "Gérard Depardieu" ('charle' is not present)
|
||||
|
||||
Rendering
|
||||
---------
|
||||
|
||||
The rendering should contains :
|
||||
|
||||
- the total number of results ;
|
||||
- the search pattern in the search language. The aim of this is to let users learn the search language easily.
|
||||
- a title
|
||||
|
||||
Frequently Asked Questions (FAQ)
|
||||
================================
|
||||
|
||||
Why renderResults returns an HTML string and not structured array ?
|
||||
It seems that the form of results may vary (according to access-right logic, ...) and is not easily structurable
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
377
docs/source/development/timelines.rst
Normal file
377
docs/source/development/timelines.rst
Normal file
@@ -0,0 +1,377 @@
|
||||
.. Copyright (C) 2015 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Timelines
|
||||
*********
|
||||
|
||||
.. contents:: Table of content
|
||||
:local:
|
||||
|
||||
Concept
|
||||
=======
|
||||
|
||||
From an user point of view
|
||||
--------------------------
|
||||
|
||||
Chill has two objectives :
|
||||
|
||||
* make the administrative tasks more lightweight ;
|
||||
* help social workers to have all information they need to work
|
||||
|
||||
To reach this second objective, Chill provides a special view: **timeline**. On a timeline view, information is gathered and shown on a single page, from the most recent event to the oldest one.
|
||||
|
||||
The information gathered is linked to a *context*. This *context* may be, for instance :
|
||||
|
||||
* a person : events linked to this person are shown on the page ;
|
||||
* a center: events linked to a center are shown. They may concern different peoples ;
|
||||
* ...
|
||||
|
||||
In other word, the *context* is the kind of argument that will be used in the event's query.
|
||||
|
||||
Let us recall that only the data the user has allowed to see should be shown.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`The issue where the subject was first discussed <https://redmine.champs-libres.coop/issues/224>`_
|
||||
|
||||
|
||||
For developers
|
||||
--------------
|
||||
|
||||
The `Main` bundle provides interfaces and services to help to build timelines.
|
||||
|
||||
If a bundle wants to *push* information in a timeline, it should be create a service which implements `Chill\MainBundle\Timeline\TimelineProviderInterface`, and tag is with `chill.timeline` and arguments defining the supported context (you may use multiple `chill.timeline` tags in order to support multiple context with a single service/class).
|
||||
|
||||
If a bundle wants to provide a new context for a timeline, the service `chill.main.timeline_builder` will helps to gather timeline's services supporting the defined context, and run queries across the models.
|
||||
|
||||
.. _understanding-queries :
|
||||
|
||||
Understanding queries
|
||||
^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Due to the fact that timelines should show only the X last events from Y differents tables, queries for a timeline may consume a lot of resources: at first on the database, and then on the ORM part, which will have to deserialize DB data to PHP classes, which may not be used if they are not part of the "last X events".
|
||||
|
||||
To avoid such load on database, the objects are queried in two steps :
|
||||
|
||||
1. An UNION request which gather the last X events, ordered by date. The data retrieved are the ID, the date, and a string key: a type. This type discriminates the data type.
|
||||
2. The PHP objects are queried by ID, the type helps the program to link id with the kind of objects.
|
||||
|
||||
Those methods should ensure that only X PHP objects will be gathered and build by the ORM.
|
||||
|
||||
What does the master timeline builder service ?
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
When the service `chill.main.timeline_builder` is instanciated, the service is informed of each service taggued with `chill.timeline` tags. Then,
|
||||
|
||||
1. The service build an UNION query by assembling column and tables names provided by the `fetchQuery` result ;
|
||||
2. The UNION query is run, the result contains an id and a type for each row (see :ref:`above <understanding-queries>`)
|
||||
3. The master service gather all id with the same type. Then he searches for the `chill.timeline`'s service which will be able to get the entities. Then, the entities will be fetched using the `fetchEntities` function. All entities are gathered in one query ;
|
||||
4. The information to render entities in HTML is gathered by passing entity, one by one, on `getEntityTemplate` function.
|
||||
|
||||
Pushing events to a timeline
|
||||
=============================
|
||||
|
||||
To push events on a timeline :
|
||||
|
||||
1. Create a class which implements `Chill\MainBundle\Timeline\TimelineProviderInterface` ;
|
||||
2. Define the class as a service, and tag the service with `chill.timeline`, and define the context associated with this timeline (you may add multiple tags for different contexts).
|
||||
|
||||
Implementing the TimelineProviderInterface
|
||||
------------------------------------------
|
||||
|
||||
The has the following signature :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\MainBundle\Timeline;
|
||||
|
||||
interface TimelineProviderInterface
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $context
|
||||
* @param mixed[] $args the argument to the context.
|
||||
* @return string[]
|
||||
* @throw \LogicException if the context is not supported
|
||||
*/
|
||||
public function fetchQuery($context, array $args);
|
||||
|
||||
/**
|
||||
* Indicate if the result type may be handled by the service
|
||||
*
|
||||
* @param string $type the key present in the SELECT query
|
||||
* @return boolean
|
||||
*/
|
||||
public function supportsType($type);
|
||||
|
||||
/**
|
||||
* fetch entities from db into an associative array. The keys **MUST BE**
|
||||
* the id
|
||||
*
|
||||
* All ids returned by all SELECT queries
|
||||
* (@see TimeLineProviderInterface::fetchQuery) and with the type
|
||||
* supported by the provider (@see TimelineProviderInterface::supportsType)
|
||||
* will be passed as argument.
|
||||
*
|
||||
* @param array $ids an array of id
|
||||
* @return mixed[] an associative array of entities, with id as key
|
||||
*/
|
||||
public function getEntities(array $ids);
|
||||
|
||||
/**
|
||||
* return an associative array with argument to render the entity
|
||||
* in an html template, which will be included in the timeline page
|
||||
*
|
||||
* The result must have the following key :
|
||||
*
|
||||
* - `template` : the template FQDN
|
||||
* - `template_data`: the data required by the template
|
||||
*
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```
|
||||
* array(
|
||||
* 'template' => 'ChillMyBundle:timeline:template.html.twig',
|
||||
* 'template_data' => array(
|
||||
* 'accompanyingPeriod' => $entity,
|
||||
* 'person' => $args['person']
|
||||
* )
|
||||
* );
|
||||
* ```
|
||||
*
|
||||
* `$context` and `$args` are defined by the bundle which will call the timeline
|
||||
* rendering.
|
||||
*
|
||||
* @param type $entity
|
||||
* @param type $context
|
||||
* @param array $args
|
||||
* @return mixed[]
|
||||
* @throws \LogicException if the context is not supported
|
||||
*/
|
||||
public function getEntityTemplate($entity, $context, array $args);
|
||||
|
||||
}
|
||||
|
||||
|
||||
The `fetchQuery` function
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
The fetchQuery function help to build the UNION query to gather events. This function should return an associative array MUST have the following key :
|
||||
|
||||
* `id` : the name of the id column
|
||||
* `type`: a string to indicate the type
|
||||
* `date`: the name of the datetime column, used to order entities by date
|
||||
* `FROM` (in capital) : the FROM clause. May contains JOIN instructions
|
||||
|
||||
Those key are optional:
|
||||
|
||||
* `WHERE` (in capital) : the WHERE clause.
|
||||
|
||||
Where relevant, the data must be quoted to avoid SQL injection.
|
||||
|
||||
`$context` and `$args` are defined by the bundle which will call the timeline rendering. You may use them to build a different query depending on this context.
|
||||
|
||||
For instance, if the context is `'person'`, the args will be this array :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
array(
|
||||
'person' => $person //a \Chill\PersonBundle\Entity\Person entity
|
||||
);
|
||||
|
||||
You should find in the bundle documentation which contexts are arguments the bundle defines.
|
||||
|
||||
.. note::
|
||||
|
||||
We encourage to use `ClassMetaData` to define column names arguments. If you change your column names, changes will be reflected automatically during the execution of your code.
|
||||
|
||||
Example of an implementation :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\ReportBundle\Timeline;
|
||||
|
||||
use Chill\MainBundle\Timeline\TimelineProviderInterface;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
|
||||
/**
|
||||
* Provide report for inclusion in timeline
|
||||
*
|
||||
* @author Julien Fastré <julien.fastre@champs-libres.coop>
|
||||
* @author Champs Libres <info@champs-libres.coop>
|
||||
*/
|
||||
class TimelineReportProvider implements TimelineProviderInterface
|
||||
{
|
||||
|
||||
/**
|
||||
*
|
||||
* @var EntityManager
|
||||
*/
|
||||
protected $em;
|
||||
|
||||
public function __construct(EntityManager $em)
|
||||
{
|
||||
$this->em = $em;
|
||||
}
|
||||
|
||||
public function fetchQuery($context, array $args)
|
||||
{
|
||||
$this->checkContext($context);
|
||||
|
||||
$metadata = $this->em->getClassMetadata('ChillReportBundle:Report');
|
||||
|
||||
return array(
|
||||
'id' => $metadata->getColumnName('id'),
|
||||
'type' => 'report',
|
||||
'date' => $metadata->getColumnName('date'),
|
||||
'FROM' => $metadata->getTableName(),
|
||||
'WHERE' => sprintf('%s = %d',
|
||||
$metadata
|
||||
->getAssociationMapping('person')['joinColumns'][0]['name'],
|
||||
$args['person']->getId())
|
||||
);
|
||||
}
|
||||
|
||||
//....
|
||||
|
||||
|
||||
}
|
||||
|
||||
The `supportsType` function
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
This function indicate to the master `chill.main.timeline_builder` service (which orchestrate the build of UNION queries) that the service supports the type indicated in the result's array of the `fetchQuery` function.
|
||||
|
||||
The implementation of our previous example will be :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
|
||||
namespace Chill\ReportBundle\Timeline;
|
||||
|
||||
use Chill\MainBundle\Timeline\TimelineProviderInterface;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
|
||||
class TimelineReportProvider implements TimelineProviderInterface
|
||||
{
|
||||
|
||||
//...
|
||||
|
||||
/**
|
||||
*
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function supportsType($type)
|
||||
{
|
||||
return $type === 'report';
|
||||
}
|
||||
|
||||
//...
|
||||
}
|
||||
|
||||
The `getEntities` function
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
This is where the service must fetch entities from database and return them to the master service.
|
||||
|
||||
The results **must be** an array where the id given by the UNION query (remember `fetchQuery`).
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\ReportBundle\Timeline;
|
||||
|
||||
use Chill\MainBundle\Timeline\TimelineProviderInterface;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
|
||||
class TimelineReportProvider implements TimelineProviderInterface
|
||||
{
|
||||
|
||||
public function getEntities(array $ids)
|
||||
{
|
||||
$reports = $this->em->getRepository('ChillReportBundle:Report')
|
||||
->findBy(array('id' => $ids));
|
||||
|
||||
$result = array();
|
||||
foreach($reports as $report) {
|
||||
$result[$report->getId()] = $report;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
The `getEntityTemplate` function
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
This is where the master service will collect information to render the entity.
|
||||
|
||||
The result must be an associative array with :
|
||||
|
||||
- **template** is the FQDN of the template ;
|
||||
- **template_data** is an associative array where keys are the variables'names for this template, and values are the values.
|
||||
|
||||
Example :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
array(
|
||||
'template' => 'ChillMyBundle:timeline:template.html.twig',
|
||||
'template_data' => array(
|
||||
'period' => $entity,
|
||||
'person' => $args['person']
|
||||
)
|
||||
);
|
||||
|
||||
The template must, obviously, exists. Example :
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
<p><i class="fa fa-folder-open"></i> {{ 'An accompanying period is opened for %person% on %date%'|trans({'%person%': person, '%date%': period.dateOpening|localizeddate('long', 'none') } ) }}</p>
|
||||
|
||||
|
||||
Create a timeline with his own context
|
||||
======================================
|
||||
|
||||
You have to create a Controller which will execute the service `chill.main.timeline_builder`. Using the `Chill\MainBundle\Timeline\TimelineBuilder::getTimelineHTML` function, you will get an HTML representation of the timeline, which you may include with twig `raw` filter.
|
||||
|
||||
Example :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Controller;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
|
||||
|
||||
class TimelinePersonController extends Controller
|
||||
{
|
||||
|
||||
public function personAction(Request $request, $person_id)
|
||||
{
|
||||
$person = $this->getDoctrine()
|
||||
->getRepository('ChillPersonBundle:Person')
|
||||
->find($person_id);
|
||||
|
||||
if ($person === NULL) {
|
||||
throw $this->createNotFoundException();
|
||||
}
|
||||
|
||||
return $this->render('ChillPersonBundle:Timeline:index.html.twig', array
|
||||
(
|
||||
'timeline' => $this->get('chill.main.timeline_builder')
|
||||
->getTimelineHTML('person', array('person' => $person)),
|
||||
'person' => $person
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
73
docs/source/development/useful-snippets.rst
Normal file
73
docs/source/development/useful-snippets.rst
Normal file
@@ -0,0 +1,73 @@
|
||||
|
||||
|
||||
|
||||
|
||||
Useful snippets
|
||||
###############
|
||||
|
||||
Dependency Injection
|
||||
********************
|
||||
|
||||
Configure route automatically
|
||||
=============================
|
||||
|
||||
Add the route for the current bundle automatically on the main app.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\MyBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
|
||||
|
||||
class ChillMyExtension extends Extension implements PrependExtensionInterface
|
||||
{
|
||||
// ...
|
||||
|
||||
public function prepend(ContainerBuilder $container)
|
||||
{
|
||||
$this->prependRoutes($container);
|
||||
|
||||
}
|
||||
|
||||
public function prependRoutes(ContainerBuilder $container)
|
||||
{
|
||||
//add routes for custom bundle
|
||||
$container->prependExtensionConfig('chill_main', array(
|
||||
'routing' => array(
|
||||
'resources' => array(
|
||||
'@ChillMyBundle/Resources/config/routing.yml'
|
||||
)
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
Security
|
||||
********
|
||||
|
||||
Get the circles a user can reach
|
||||
================================
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
use Symfony\Component\Security\Core\Role\Role;
|
||||
|
||||
$authorizationHelper = $this->get('chill.main.security.authorization.helper');
|
||||
$circles = $authorizationHelper
|
||||
->getReachableCircles(
|
||||
$this->getUser(), # from a controller
|
||||
new Role('CHILL_ROLE'),
|
||||
$center
|
||||
);
|
||||
|
||||
|
||||
Controller
|
||||
**********
|
||||
|
||||
Secured controller for person
|
||||
=============================
|
||||
|
||||
.. literalinclude:: useful-snippets/controller-secured-for-person.php
|
||||
:language: php
|
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\HealthBundle\Controller;
|
||||
|
||||
use Chill\HealthBundle\Security\Authorization\ConsultationVoter;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
|
||||
use Chill\PersonBundle\Security\Authorization\PersonVoter;
|
||||
use Symfony\Component\Security\Core\Role\Role;
|
||||
|
||||
class ConsultationController extends Controller
|
||||
{
|
||||
/**
|
||||
*
|
||||
* @param int $id personId
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
* @throws type
|
||||
*/
|
||||
public function listAction($id)
|
||||
{
|
||||
/* @var $person \Chill\PersonBundle\Entity\Person */
|
||||
$person = $this->get('chill.person.repository.person')
|
||||
->find($id);
|
||||
|
||||
if ($person === null) {
|
||||
throw $this->createNotFoundException("The person is not found");
|
||||
}
|
||||
|
||||
$this->denyAccessUnlessGranted(PersonVoter::SEE, $person);
|
||||
|
||||
/* @var $authorizationHelper \Chill\MainBundle\Security\Authorization\AuthorizationHelper */
|
||||
$authorizationHelper = $this->get('chill.main.security.'
|
||||
. 'authorization.helper');
|
||||
|
||||
$circles = $authorizationHelper->getReachableCircles(
|
||||
$this->getUser(),
|
||||
new Role(ConsultationVoter::SEE),
|
||||
$person->getCenter()
|
||||
);
|
||||
|
||||
// create a query which take circles into account
|
||||
$consultations = $this->getDoctrine()->getManager()
|
||||
->createQuery('SELECT c FROM ChillHealthBundle:Consultation c '
|
||||
. 'WHERE c.patient = :person AND c.circle IN(:circles) '
|
||||
. 'ORDER BY c.date DESC')
|
||||
->setParameter('person', $person)
|
||||
->setParameter('circles', $circles)
|
||||
->getResult();
|
||||
|
||||
return $this->render('ChillHealthBundle:Consultation:list.html.twig', array(
|
||||
'person' => $person,
|
||||
'consultations' => $consultations
|
||||
));
|
||||
}
|
||||
}
|
||||
|
77
docs/source/development/user-interface/css-classes.rst
Normal file
77
docs/source/development/user-interface/css-classes.rst
Normal file
@@ -0,0 +1,77 @@
|
||||
.. Copyright (C) 2016 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
CSS classes and mixins
|
||||
######################
|
||||
|
||||
The stylesheet are based on the framework `ScratchCSS <https://github.com/Champs-Libres/ScratchCSS>`_.
|
||||
|
||||
We added some useful classes and mixins for the Chill usage.
|
||||
|
||||
CSS Classes
|
||||
************
|
||||
|
||||
|
||||
Statement "empty data"
|
||||
======================
|
||||
|
||||
CSS Selector
|
||||
:code:`.chill-no-data-statement`
|
||||
In which case will you use this selector ?
|
||||
When a list is empty, and a message fill the list to inform that the data is empty
|
||||
Example usage
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<span class="chill-no-data-statement">{{ 'No reason associated'|trans }}</span>
|
||||
|
||||
|
||||
Quotation of user text
|
||||
=======================
|
||||
|
||||
CSS Selector
|
||||
:code:`blockquote.chill-user-quote`
|
||||
In which case will you use this selector ?
|
||||
When you quote text that were filled by the user in a form.
|
||||
Example usage
|
||||
.. code-block:: html+jinja
|
||||
|
||||
<blockquote class="chill-user-quote">{{ entity.remark|nl2br }}</blockquote>
|
||||
|
||||
Boxes
|
||||
=====
|
||||
|
||||
CSS Selector
|
||||
:code:`chill__box`
|
||||
In which case will you use this selector ?
|
||||
When displaying some data in a nice box
|
||||
Example usage
|
||||
.. code-block:: html+twig
|
||||
|
||||
<span class="chill__box green">A nice box with green background</span>
|
||||
<span class="chill__box red">A nice box with red background</span>
|
||||
|
||||
|
||||
|
||||
Mixins
|
||||
******
|
||||
|
||||
|
||||
Entity decorator
|
||||
=================
|
||||
|
||||
Mixin
|
||||
:code:`@mixin entity($background-color, $color: white)`
|
||||
In which case including this mixin ?
|
||||
When you create a `sticker`, a sort of label to represent a text in a way that the user can associate immediatly with a certain type of class / entity.
|
||||
Example usage
|
||||
.. code-block:: sass
|
||||
|
||||
span.entity.entity-activity.activity-reason {
|
||||
@include entity($chill-pink, white);
|
||||
}
|
261
docs/source/development/user-interface/js-functions.rst
Normal file
261
docs/source/development/user-interface/js-functions.rst
Normal file
@@ -0,0 +1,261 @@
|
||||
.. Copyright (C) 2016 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Javascript functions
|
||||
####################
|
||||
|
||||
Some function may be useful to manipulate elements on the page.
|
||||
|
||||
Show-hide elements according to a form state
|
||||
*********************************************
|
||||
|
||||
The module ``ShowHide`` will allow you to show/hide part of your page using a specific test.
|
||||
|
||||
This must be use inside a javascript module.
|
||||
|
||||
Usage
|
||||
=====
|
||||
|
||||
In this module, the module will listen to all input given in the ``container_from`` div, and will show or hide the content of the ``container_target`` according to the result of the ``test`` function.
|
||||
|
||||
.. code-block:: html+twig
|
||||
|
||||
<div id="container_from">
|
||||
{{ form_row(form.accompagnementRQTHDate) }}
|
||||
</div>
|
||||
|
||||
<div id="container_target">
|
||||
{{ form_row(form.accompagnementComment) }}
|
||||
</div>
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
import { ShowHide } from 'ShowHide/show_hide.js';
|
||||
|
||||
var
|
||||
from = document.getElementById("container_from"),
|
||||
target = document.getElementById("container_target")
|
||||
;
|
||||
|
||||
new ShowHide({
|
||||
froms: [from], // the value of from should be an iterable
|
||||
container: [target], // the value of container should be an iterable
|
||||
test: function(froms, event) {
|
||||
// iterate over each element of froms
|
||||
for (let f of froms.values()) {
|
||||
// get all input inside froms
|
||||
for (let input of f.querySelectorAll('input').values()) {
|
||||
if (input.value === 'autre') {
|
||||
return input.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
Once instantiated, the class ``ShowHide`` will:
|
||||
|
||||
1. get all input from each element inside the ``froms`` values
|
||||
2. attach an event listener (by default, ``change``) to each input inside each entry in ``froms``
|
||||
3. each time the event is fired, launch the function ``test``
|
||||
4. show the element in the container given in ``container``, if the result of ``test`` is true, or hide them otherwise.
|
||||
|
||||
The test is also launched when the page is loaded.
|
||||
|
||||
Show/hide while the user enter data: using the ``input`` event
|
||||
==============================================================
|
||||
|
||||
One can force to use another event on the input elements, instead of the default ``'change'`` event.
|
||||
|
||||
For achieving this, use the `event_name` option.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
new ShowHide({
|
||||
froms: froms,
|
||||
test: test_function,
|
||||
container: containers ,
|
||||
// using this option, we use the event `input` instead of `change`
|
||||
event_name: 'input'
|
||||
});
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
.. literalinclude:: js-functions/show_hide.js
|
||||
:language: javascript
|
||||
|
||||
|
||||
Using Show/Hide in collections forms
|
||||
====================================
|
||||
|
||||
Using show / hide in collection forms implies:
|
||||
|
||||
* to launch show/hide manually for each entry when the page is loaded ;
|
||||
* to catch when an entry is added to the form ;
|
||||
|
||||
As the show/hide is started manually and not on page load, we add the option ``load_event: null`` to the options:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
new ShowHide({
|
||||
load_event: null,
|
||||
froms: [ from ],
|
||||
container: [ container ],
|
||||
test: my_test_function
|
||||
});
|
||||
|
||||
.. note::
|
||||
|
||||
When using ``load_event: null`` inside the options, the value of event will be ``null`` as second argument for the test function.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
my_test_function(froms, event) {
|
||||
// event will be null on first launch
|
||||
}
|
||||
|
||||
Example usage: here, we would like to catch for element inside a CV form, where the user may add multiple formation entries.
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
import { ShowHide } from 'ShowHide/show_hide.js';
|
||||
|
||||
// we factorize the creation of show hide element in this function.
|
||||
var make_show_hide = function(entry) {
|
||||
let
|
||||
obtained = entry.querySelector('[data-diploma-obtained]'),
|
||||
reconnue = entry.querySelector('[data-diploma-reconnue]')
|
||||
;
|
||||
new ShowHide({
|
||||
load_event: null,
|
||||
froms: [ obtained ],
|
||||
container: [ reconnue ],
|
||||
test: my_test_function
|
||||
});
|
||||
};
|
||||
|
||||
// this code is fired when an entry is added on the page
|
||||
window.addEventListener('collection-add-entry', function(e) {
|
||||
// if the form contains multiple collection, we filter them here:
|
||||
if (e.detail.collection.dataset.collectionName === 'formations') {
|
||||
make_show_hide(e.detail.entry);
|
||||
}
|
||||
});
|
||||
|
||||
// on page load, we create a show/hide
|
||||
window.addEventListener('load', function(_e) {
|
||||
let
|
||||
formations = document.querySelectorAll('[data-formation-entry]')
|
||||
;
|
||||
|
||||
for (let f of formations.values()) {
|
||||
make_show_hide(f);
|
||||
}
|
||||
});
|
||||
|
||||
Handling encapsulated show/hide elements
|
||||
========================================
|
||||
|
||||
This module allow to handle encapsulated show/hide elements. For instance :
|
||||
|
||||
* in a first checkbox list, a second checkbox list is shown if some element is checked ;
|
||||
* in this second checkbox list, a third input is shown if some element is checked inside the second checkbox list.
|
||||
|
||||
As a consequence, if the given element in the first checkbox list is unchecked, the third input must also be hidden.
|
||||
|
||||
Example: when a situation professionnelle is ``en activite``, the second element ``type contrat`` must be shown if ``en_activite`` is checked. Inside ``type_contrat``, ``type_contrat_aide`` should be shown when ``contrat_aide`` is checked.
|
||||
|
||||
.. code-block:: html
|
||||
|
||||
<div id="situation_prof">
|
||||
<input type="radio" name="situationProfessionnelle" value="" checked="checked" />
|
||||
<input type="radio" name="situationProfessionnelle" value="sans_emploi" />
|
||||
<input type="radio" name="situationProfessionnelle" value="en_activite" />
|
||||
</div>
|
||||
|
||||
|
||||
<div id="type_contrat">
|
||||
<input type="checkbox" name="typeContrat[]" value="cdd" />
|
||||
<input type="checkbox" name="typeContrat[]" value="cdi" />
|
||||
<input type="checkbox" name="typeContrat[]" value="contrat_aide" />
|
||||
</div>
|
||||
|
||||
<div id="type_contrat_aide">
|
||||
<input type="text" name="typeContratAide" />
|
||||
</div>
|
||||
|
||||
The JS code will be:
|
||||
|
||||
.. code-block:: javascript
|
||||
|
||||
import { ShowHide } from 'ShowHide/show_hide.js';
|
||||
// we search for the element within the DOM
|
||||
// NOTE: all the elements should be searched before instanciating the showHides.
|
||||
// if not, the elements **may** have disappeared from the DOM
|
||||
|
||||
var
|
||||
situation_prof = document.getElementById('situation_prof'),
|
||||
type_contrat = document.getElementById('type_contrat'),
|
||||
type_contrat_aide = document.getElementById('type_contrat_aide'),
|
||||
;
|
||||
|
||||
// the first show/hide will apply on situation_prof
|
||||
new ShowHide({
|
||||
// the id will help us to keep a track of the element
|
||||
id: 'situation_prof_type_contrat',
|
||||
froms: [situation_prof],
|
||||
container: [type_contrat],
|
||||
test: function(froms) {
|
||||
for (let f of froms.values()) {
|
||||
for (let input of f.querySelectorAll('input').values()) {
|
||||
if (input.value === 'en_activite') {
|
||||
return input.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// the show/hide will apply on "contrat aide"
|
||||
var show_hide_contrat_aide = new ShowHide({
|
||||
froms: [type_contrat],
|
||||
container: [type_contrat_aide],
|
||||
test: function(froms) {
|
||||
for (let f of froms.values()) {
|
||||
for (let input of f.querySelectorAll('input').values()) {
|
||||
if (input.value === 'contrat_aide') {
|
||||
return input.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// we handle here the case when the first show-hide is changed: the third input must also disappears
|
||||
window.addEventListener('show-hide-hide', function (e) {
|
||||
if (e.detail.id = 'situation_prof_type_contrat') {
|
||||
// we force the 3rd element to disappears
|
||||
show_hide_contrat_aide.forceHide();
|
||||
}
|
||||
});
|
||||
|
||||
// when the first show-hide is changed, it makes appears the second one.
|
||||
// we check here that the second show-hide is processed.
|
||||
window.addEventListener('show-hide-show', function (e) {
|
||||
if (e.detail.id = 'situation_prof_type_contrat') {
|
||||
show_hide_contrat_aide.forceCompute();
|
||||
}
|
||||
});
|
@@ -0,0 +1,39 @@
|
||||
import { ShowHide } from 'ShowHide/show_hide.js';
|
||||
|
||||
var
|
||||
div_accompagnement = document.getElementById("form_accompagnement"),
|
||||
div_accompagnement_comment = document.getElementById("form_accompagnement_comment"),
|
||||
div_caf_id = document.getElementById("cafId"),
|
||||
div_caf_inscription_date = document.getElementById("cafInscriptionDate"),
|
||||
;
|
||||
|
||||
// let show/hide the div_accompagnement_comment if the input with value `'autre'` is checked
|
||||
new ShowHide({
|
||||
"froms": [div_accompagnement],
|
||||
"test": function(froms, event) {
|
||||
for (let el of froms.values()) {
|
||||
for (let input of el.querySelectorAll('input').values()) {
|
||||
if (input.value === 'autre') {
|
||||
return input.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
"container": [div_accompagnement_comment]
|
||||
});
|
||||
|
||||
// let show the date input only if the the id is filled
|
||||
new ShowHide({
|
||||
froms: [ div_caf_id ],
|
||||
test: function(froms, event) {
|
||||
for (let el of froms.values()) {
|
||||
return el.querySelector("input").value !== "";
|
||||
}
|
||||
},
|
||||
container: [ div_caf_inscription_date ],
|
||||
// using this option, we use the event `input` instead of `change`
|
||||
event_name: 'input'
|
||||
});
|
||||
|
225
docs/source/development/user-interface/layout-template-usage.rst
Normal file
225
docs/source/development/user-interface/layout-template-usage.rst
Normal file
@@ -0,0 +1,225 @@
|
||||
.. Copyright (C) 2015 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
|
||||
Layout / Template usage
|
||||
#######################
|
||||
|
||||
We recommand the use of the existing layouts to ensure the consistency of the design. This section explains the different templates and how to use it.
|
||||
|
||||
The layouts are twig templates.
|
||||
|
||||
Twig templating helper
|
||||
======================
|
||||
|
||||
`chill_print_or_message`
|
||||
------------------------
|
||||
|
||||
Print a value or use a default template if the value is empty.
|
||||
|
||||
The template can be customized.
|
||||
|
||||
Two default templates are registered:
|
||||
|
||||
- :code:`default`, do not decorate the value ;
|
||||
- :code:`blockquote`: wrap the value into a blockquote if exists
|
||||
|
||||
.. code-block:: html+twig
|
||||
|
||||
{{ "This is a message"|chill_print_or_message("No message") }}
|
||||
<!-- will print "This is a message" -->
|
||||
|
||||
{{ ""|chill_print_or_message("No message")}}
|
||||
<!-- will print <span class="chill-no-data-statement">No message</span> -->
|
||||
|
||||
{{ "This is a comment\n with multiples lines"|chill_print_or_message("No comment", 'blockquote') }}
|
||||
<!-- will print <blockquote class="chill-user-quote">This is a comment<br/>with multiples lines</blockquote> -->
|
||||
|
||||
When customizing the template, two arguments are passed to the template:
|
||||
|
||||
- :code:`value`: the actual value ;
|
||||
- :code:`message`: the message, given as argument
|
||||
|
||||
Routing with return path
|
||||
------------------------
|
||||
|
||||
Three twig function are available for creating routes and handling "return path".
|
||||
|
||||
**Rationale**: When building a "CRUD" (CReate, Update, Delete of an entity), you would like to allow people to go back on some custom cancel page when coming for another place of an application. For instance, if you are in the timeline and show an activity, you would like that the user go back to the timeline when pressing the "return" button at the bottom of the page, instead of going back to the "activity list" page.
|
||||
|
||||
Using those function, a :code:`returnPath` parameter will be added in the path generated. It will be used instead of the default one in the subsequente pages.
|
||||
|
||||
- :code:`chill_path_add_return_path(name, parameters = [], relative = false)`: will create a path with current page as return path (users will go back to the current page on the next page) ;
|
||||
- :code:`chill_return_path_or(name, parameters = [], relative = false)`: will create a path to the return path if present, or build the path according to the given parameters ;
|
||||
- :code:`chill_path_forward_return_path(name, parameters = [], relative = false)`: will create a path and adding the return path that is present for the current page, *forwarding* the return path to the next page. This is useful if you are on a "show" page with a return path (by instance, the "timeline" page), you place a link to the *edit* page and want users to go back to the "timeline" page on the edit page.
|
||||
|
||||
|
||||
- :code:`chill_return_path_or`:
|
||||
|
||||
|
||||
Organisation of the layouts
|
||||
===========================
|
||||
|
||||
ChillMainBundle::layout.html.twig
|
||||
---------------------------------
|
||||
|
||||
This is the base layout. It includes the most import css / js files. It display a page with
|
||||
|
||||
* a horizontal navigation menu
|
||||
* a place for content
|
||||
* a footer
|
||||
|
||||
|
||||
The layout containts blocks, that are :
|
||||
|
||||
* title
|
||||
|
||||
* to display title
|
||||
|
||||
* css
|
||||
|
||||
* where to add some custom css
|
||||
|
||||
* navigation_section_menu
|
||||
|
||||
* place where to insert the section menu in the navigation menu (by default the navigation menu is inserted)
|
||||
|
||||
* navigation_search_bar
|
||||
|
||||
* place where to insert a search bar in the navigation menu (by default the search bar is inserted)
|
||||
|
||||
* top_banner
|
||||
|
||||
* place where to display a banner below the navigation menu (this place is use to display the details of the person)
|
||||
|
||||
* sublayout_containter
|
||||
|
||||
* place between the header and the footer that can be used to create a new layout (with vertical menu for example)
|
||||
|
||||
* content
|
||||
|
||||
* place where to display the content (flash message are included outside of this block)
|
||||
|
||||
* js
|
||||
|
||||
* where to add some custom javascript
|
||||
|
||||
|
||||
ChillMainBundle::layoutWithVerticalMenu.html.twig
|
||||
-------------------------------------------------
|
||||
|
||||
This layout extends `ChillMainBundle::layout.html.twig`. It replaces the block `layout_content` and divides this block for displaying a vertical menu and some content.
|
||||
|
||||
It proposes 2 new blocks :
|
||||
|
||||
* layout_wvm_content
|
||||
|
||||
* where to display the page content
|
||||
|
||||
* vertical_menu_content
|
||||
|
||||
* where to place the vertical menu
|
||||
|
||||
|
||||
ChillMainBundle::Admin/layout.html.twig
|
||||
---------------------------------------
|
||||
|
||||
This layout extends `ChillMainBundle::layout.html.twig`. It hides the search bar, remplaces the `section menu` with the `admin section menu`.
|
||||
|
||||
It proposes a new block :
|
||||
|
||||
* admin_content
|
||||
|
||||
* where to display the admin content
|
||||
|
||||
|
||||
ChillMainBundle::Admin/layoutWithVerticalMenu.html.twig
|
||||
-------------------------------------------------------
|
||||
|
||||
This layout extends `ChillMainBundle::layoutWithVerticalMenu.html.twig`. It do the same changes than `ChillMainBundle::Admin/layout.html.twig` : hiding the search bar, remplacing the `section menu` with the `admin section menu`.
|
||||
|
||||
It proposes a new block :
|
||||
|
||||
* admin_content
|
||||
|
||||
* where to display the admin content
|
||||
|
||||
ChillPersonBundle::layout.html.twig
|
||||
-----------------------------------
|
||||
|
||||
This layout extend `ChillMainBundle::layoutWithVerticalMenu.html.twig` add the person details in the block `top_banner`, set the menu `person` as the vertical menu.
|
||||
|
||||
It proposes 1 new block :
|
||||
|
||||
* personcontent
|
||||
|
||||
* where to display the information of the person
|
||||
|
||||
|
||||
ChillMainBundle::Export/layout.html.twig
|
||||
----------------------------------------
|
||||
|
||||
This layout extends `ChillMainBundle::layoutWithVerticalMenu.html.twig` and set the menu `export` as the vertical menu.
|
||||
|
||||
It proposes 1 new block :
|
||||
|
||||
* export_content
|
||||
|
||||
* where to display the content of the export
|
||||
|
||||
Useful template and helpers
|
||||
===========================
|
||||
|
||||
Macros
|
||||
------
|
||||
|
||||
Every bundle may bring their own macro to print resources with uniformized styles.
|
||||
|
||||
See :
|
||||
|
||||
- :ref:`Macros in person bundle <person-bundle-macros>` ;
|
||||
- :ref:`Macros in activity bundle <activity-bundle-macros>` ;
|
||||
- :ref:`Macros in group bundle <group-bundle-macros>` ;
|
||||
- :ref:`Macros in main bundle <main-bundle-macros>` ;
|
||||
|
||||
Templates
|
||||
---------
|
||||
|
||||
ChillMainBundle::Util:confirmation_template.html.twig
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
This template show a confirmation template before making dangerous things. You can add your own message and title, or define those message by yourself in another template.
|
||||
|
||||
The accepted parameters are :
|
||||
|
||||
- `title` (string) a title for the page. Not mandatory (it won't be rendered if not defined)
|
||||
- `confirm_question` (string) a confirmation question. This question will not be translated into the template, and may be printed as raw. Not mandatory (it won't be rendered if not defined)
|
||||
- `form` : (:class:`Symfony\Component\Form\FormView`) a form wich **must** contains an input named `submit`, which must be a :class:`Symfony\Component\Form\Extension\Core\Type\SubmitType`. Mandatory
|
||||
- `cancel_route` : (string) the name of a route if the user want to cancel the action
|
||||
- `cancel_parameters` (array) the parameters for the route defined in `cancel_route`
|
||||
|
||||
|
||||
Usage :
|
||||
|
||||
|
||||
.. code-block:: html+twig
|
||||
|
||||
{{ include('ChillMainBundle:Util:confirmation_template.html.twig',
|
||||
{
|
||||
# a title, not mandatory
|
||||
'title' : 'Remove membership'|trans,
|
||||
# a confirmation question, not mandatory
|
||||
'confirm_question' : 'Are you sure you want to remove membership ?'|trans
|
||||
# a route for "cancel" button (mandatory)
|
||||
'cancel_route' : 'chill_group_membership_by_person',
|
||||
# the parameters for 'cancel' route (default to {} )
|
||||
'cancel_parameters' : { 'person_id' : membership.person.id },
|
||||
# the form which will send the deletion. This form
|
||||
# **must** contains a SubmitType
|
||||
'form' : form
|
||||
} ) }}
|
333
docs/source/development/user-interface/widgets.rst
Normal file
333
docs/source/development/user-interface/widgets.rst
Normal file
@@ -0,0 +1,333 @@
|
||||
.. Copyright (C) 2016 Champs Libres Cooperative SCRLFS
|
||||
Permission is granted to copy, distribute and/or modify this document
|
||||
under the terms of the GNU Free Documentation License, Version 1.3
|
||||
or any later version published by the Free Software Foundation;
|
||||
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
A copy of the license is included in the section entitled "GNU
|
||||
Free Documentation License".
|
||||
|
||||
Widgets
|
||||
##############################################
|
||||
|
||||
Rationale
|
||||
=========
|
||||
|
||||
Widgets are useful if you want to publish content on a page provided by another bundle.
|
||||
|
||||
|
||||
Examples :
|
||||
|
||||
- you want to publish a list of people on the homepage ;
|
||||
- you may want to show the group belonging (see :ref:`group-bundle`) below of the vertical menu, only if the bundle is installed.
|
||||
|
||||
The administrator of the chill instance may configure the presence of widget. Although, some widget are defined by default (see :ref:`declaring-widget-by-default`).
|
||||
|
||||
Concepts
|
||||
========
|
||||
|
||||
A bundle may define *place(s)* where a widget may be rendered.
|
||||
|
||||
In a single *place*, zero, one or more *widget* may be displayed.
|
||||
|
||||
Some *widget* may require some *configuration*, and some does not require any configuration.
|
||||
|
||||
Example:
|
||||
|
||||
=========================================== ======== ============================= =======================================
|
||||
Use case place place defined by... widget provided by...
|
||||
=========================================== ======== ============================= =======================================
|
||||
Publishing a list of people on the homepage homepage defined by :ref:`main-bundle` widget provided by :ref:`person-bundle`
|
||||
=========================================== ======== ============================= =======================================
|
||||
|
||||
|
||||
|
||||
Creating a widget without configuration
|
||||
========================================
|
||||
|
||||
To add a widget, you should :
|
||||
|
||||
- define your widget, implementing :class:`Chill\MainBundle\Templating\Widget\WidgetInterface` ;
|
||||
- declare your widget with tag `chill_widget`.
|
||||
|
||||
|
||||
Define the widget class
|
||||
-----------------------
|
||||
|
||||
Define your widget class by implemeting :class:`Chill\MainBundle\Templating\Widget\WidgetInterface`.
|
||||
|
||||
Example :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\PersonBundle\Widget;
|
||||
|
||||
use Chill\MainBundle\Templating\Widget\WidgetInterface;
|
||||
|
||||
|
||||
/**
|
||||
* Add a button "add a person"
|
||||
*
|
||||
*/
|
||||
class AddAPersonWidget implements WidgetInterface
|
||||
{
|
||||
public function render(
|
||||
\Twig_Environment $env,
|
||||
$place,
|
||||
array $context,
|
||||
array $config
|
||||
) {
|
||||
// this will render a link to the page "add a person"
|
||||
return $env->render("ChillPersonBundle:Widget:homepage_add_a_person.html.twig");
|
||||
}
|
||||
}
|
||||
|
||||
Arguments are :
|
||||
|
||||
- :code:`$env` the :class:`\Twig_Environment`, which you can use to render your widget ;
|
||||
- :code:`$place` a string representing the place where the widget is rendered ;
|
||||
- :code:`$context` the context given by the template ;
|
||||
- :code:`$config` the configuration which is, in this case, always an empty array (see :ref:`creating-a-widget-with-config`).
|
||||
|
||||
.. note::
|
||||
|
||||
The html returned by the :code:`render` function will be considered as html safe. You should strip html before returning it. See also `How to escape output in template <http://symfony.com/doc/current/templating/escaping.html>`_.
|
||||
|
||||
|
||||
Declare your widget
|
||||
-------------------
|
||||
|
||||
Declare your widget as a service and add it the tag :code:`chill_widget`:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
service:
|
||||
chill_person.widget.add_person:
|
||||
class: Chill\PersonBundle\Widget\AddAPersonWidget
|
||||
tags:
|
||||
- { name: chill_widget, alias: add_person, place: homepage }
|
||||
|
||||
|
||||
The tag must contains those arguments :
|
||||
|
||||
- :code:`alias`: an alias, which will be used to reference the widget into the config
|
||||
- :code:`place`: a place where this widget is authorized
|
||||
|
||||
If you want your widget to be available on multiple places, you should add one tag with each place.
|
||||
|
||||
Conclusion
|
||||
----------
|
||||
|
||||
Once your widget is correctly declared, your widget should be available in configuration.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ php app/console config:dump-reference chill_main
|
||||
# Default configuration for extension with alias: "chill_main"
|
||||
chill_main:
|
||||
[...]
|
||||
# register widgets on place "homepage"
|
||||
homepage:
|
||||
|
||||
# the ordering of the widget. May be a number with decimal
|
||||
order: ~ # Required, Example: 10.58
|
||||
|
||||
# the widget alias (see your installed bundles config). Possible values are (maybe incomplete) : person_list, add_person
|
||||
widget_alias: ~ # Required
|
||||
|
||||
If you want to add your widget by default, see :ref:`declaring-widget-by-default`.
|
||||
|
||||
.. _creating-a-widget-with-config:
|
||||
|
||||
Creating a widget **with** configuration
|
||||
========================================
|
||||
|
||||
You can declare some configuration with your widget, which allow administrators to add their own configuration.
|
||||
|
||||
To add some configuration, you will :
|
||||
|
||||
- declare a widget as defined above ;
|
||||
- optionnaly declare it as a service ;
|
||||
- add a widget factory, which will add configuration to the bundle which provide the place.
|
||||
|
||||
|
||||
Declare your widget class
|
||||
-------------------------
|
||||
|
||||
Declare your widget. You can use some configuration elements in your process, as used here :
|
||||
|
||||
.. literalinclude:: ./widgets/ChillPersonAddAPersonWidget.php
|
||||
:language: php
|
||||
|
||||
Declare your widget as a service
|
||||
--------------------------------
|
||||
|
||||
You can declare your widget as a service. Not tag is required, as the service will be defined by the :code:`Factory` during next step.
|
||||
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
services:
|
||||
chill_person.widget.person_list:
|
||||
class: Chill\PersonBundle\Widget\PersonListWidget
|
||||
arguments:
|
||||
- "@chill.person.repository.person"
|
||||
- "@doctrine.orm.entity_manager"
|
||||
- "@chill.main.security.authorization.helper"
|
||||
- "@security.token_storage"
|
||||
# this widget is defined by the PersonListWidgetFactory
|
||||
|
||||
You can eventually skip this step and declare your service into the container through the factory (see above).
|
||||
|
||||
Declare your widget factory
|
||||
---------------------------
|
||||
|
||||
The widget factory must implements `Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface`. For your convenience, an :class:`Chill\MainBundle\DependencyInjection\Widget\Factory\AbstractWidgetFactory` will already implements some easy method.
|
||||
|
||||
.. literalinclude:: ./widgets/ChillPersonAddAPersonListWidgetFactory.php
|
||||
:language: php
|
||||
|
||||
.. note::
|
||||
You can declare your widget into the container by overriding the `createDefinition` method. By default, this method will return the already existing service definition with the id given by :code:`getServiceId`. But you can create or adapt programmatically the definition. `See the symfony doc on how to do it <http://symfony.com/doc/current/service_container/definitions.html#working-with-a-definition>`_.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
public function createDefinition(ContainerBuilder $containerBuilder, $place, $order, array $config)
|
||||
{
|
||||
$definition = new \Symfony\Component\DependencyInjection\Definition('my\Class');
|
||||
// create or adapt your definition here
|
||||
|
||||
return $definition;
|
||||
}
|
||||
|
||||
You must then register your factory into the :code:`Extension` class which provide the place. This is done in the :code: `Bundle` class.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
# Chill/PersonBundle/ChillPersonBundle.php
|
||||
|
||||
use Symfony\Component\HttpKernel\Bundle\Bundle;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Chill\PersonBundle\Widget\PersonListWidgetFactory;
|
||||
|
||||
class ChillPersonBundle extends Bundle
|
||||
{
|
||||
public function build(ContainerBuilder $container)
|
||||
{
|
||||
parent::build($container);
|
||||
|
||||
$container->getExtension('chill_main')
|
||||
->addWidgetFactory(new PersonListWidgetFactory());
|
||||
}
|
||||
}
|
||||
|
||||
.. _declaring-widget-by-default:
|
||||
|
||||
Declaring a widget by default
|
||||
=============================
|
||||
|
||||
Use the ability `to prepend configuration of other bundle <http://symfony.com/doc/current/bundles/prepend_extension.html>`_. A living example here :
|
||||
|
||||
.. literalinclude:: ./widgets/ChillPersonExtension.php
|
||||
:language: php
|
||||
|
||||
|
||||
Defining a place
|
||||
================
|
||||
|
||||
Add your place in template
|
||||
--------------------------
|
||||
|
||||
A place should be defined by using the :code:`chill_widget` function, which take as argument :
|
||||
|
||||
- :code:`place` (string) a string defining the place ;
|
||||
- :code:`context` (array) an array defining the context.
|
||||
|
||||
The context should be documented by the bundle. It will give some information about the context of the page. Example: if the page concerns a people, the :class:`Chill\PersonBundle\Entity\Person` class will be in the context.
|
||||
|
||||
Example :
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{# an empty context on homepage #}
|
||||
{{ chill_widget('homepage', {} }}
|
||||
|
||||
.. code-block:: html+jinja
|
||||
|
||||
{# defining a place 'right column' with the person currently viewed
|
||||
{{ chill_widget('right_column', { 'person' : person } }}
|
||||
|
||||
|
||||
Declare configuration for you place
|
||||
-----------------------------------
|
||||
|
||||
In order to let other bundle, or user, to define the widgets inside the given place, you should open a configuration. You can use the Trait :class:`Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait`, which provide the method `addWidgetConfiguration($place, ContainerBuilder $container)`.
|
||||
|
||||
Example :
|
||||
|
||||
.. literalinclude:: ./widgets/ChillMainConfiguration.php
|
||||
:language: php
|
||||
:emphasize-lines: 17, 30, 32, 52
|
||||
:linenos:
|
||||
|
||||
.. _example-chill-main-extension:
|
||||
|
||||
You should also adapt the :class:`DependencyInjection\*Extension` class to add ContainerBuilder and WidgetFactories :
|
||||
|
||||
.. literalinclude:: ./widgets/ChillMainExtension.php
|
||||
:language: php
|
||||
:emphasize-lines: 25-39, 48-49, 56
|
||||
:linenos:
|
||||
|
||||
- line 25-39: we implements the method required by :class:`Chill\MainBundle\DependencyInjection\Widget\HasWidgetExtensionInterface` ;
|
||||
- line 48-49: we record the configuration of widget into container's parameter ;
|
||||
- line 56 : we create an instance of :class:`Configuration` (declared above)
|
||||
|
||||
Compile the possible widget using Compiler pass
|
||||
-----------------------------------------------
|
||||
|
||||
For your convenience, simply extends :class:`Chill\MainBundle\DependencyInjection\Widget\AbstractWidgetsCompilerPass`. This class provides a `doProcess(ContainerBuildere $container, $extension, $parameterName)` method which will do the job for you:
|
||||
|
||||
- :code:`$container` is the container builder
|
||||
- :code:`$extension` is the extension name
|
||||
- :code:`$parameterName` is the name of the parameter which contains the configuration for widgets (see :ref:`the example with ChillMain above <example-chill-main-extension>`.
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Chill\MainBundle\DependencyInjection\Widget\AbstractWidgetsCompilerPass;
|
||||
|
||||
/**
|
||||
* Compile the service definition to register widgets.
|
||||
*
|
||||
*/
|
||||
class WidgetsCompilerPass extends AbstractWidgetsCompilerPass {
|
||||
|
||||
public function process(ContainerBuilder $container)
|
||||
{
|
||||
$this->doProcess($container, 'chill_main', 'chill_main.widgets');
|
||||
}
|
||||
}
|
||||
|
||||
As explained `in the symfony docs <http://symfony.com/doc/current/service_container/compiler_passes.html>`_, you should register your Compiler Pass into your bundle :
|
||||
|
||||
.. code-block:: php
|
||||
|
||||
namespace Chill\MainBundle;
|
||||
|
||||
use Symfony\Component\HttpKernel\Bundle\Bundle;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\WidgetsCompilerPass;
|
||||
|
||||
|
||||
class ChillMainBundle extends Bundle
|
||||
{
|
||||
public function build(ContainerBuilder $container)
|
||||
{
|
||||
parent::build($container);
|
||||
$container->addCompilerPass(new WidgetsCompilerPass());
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
# Chill\MainBundle\DependencyInjection\Configuration.php
|
||||
|
||||
namespace Chill\MainBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
|
||||
use Symfony\Component\Config\Definition\ConfigurationInterface;
|
||||
use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
|
||||
/**
|
||||
* Configure the main bundle
|
||||
*/
|
||||
class Configuration implements ConfigurationInterface
|
||||
{
|
||||
|
||||
use AddWidgetConfigurationTrait;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var ContainerBuilder
|
||||
*/
|
||||
private $containerBuilder;
|
||||
|
||||
|
||||
public function __construct(array $widgetFactories = array(),
|
||||
ContainerBuilder $containerBuilder)
|
||||
{
|
||||
// we register here widget factories (see below)
|
||||
$this->setWidgetFactories($widgetFactories);
|
||||
// we will need the container builder later...
|
||||
$this->containerBuilder = $containerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getConfigTreeBuilder()
|
||||
{
|
||||
$treeBuilder = new TreeBuilder();
|
||||
$rootNode = $treeBuilder->root('chill_main');
|
||||
|
||||
$rootNode
|
||||
->children()
|
||||
|
||||
// ...
|
||||
|
||||
->arrayNode('widgets')
|
||||
->canBeDisabled()
|
||||
->children()
|
||||
// we declare here all configuration for homepage place
|
||||
->append($this->addWidgetsConfiguration('homepage', $this->containerBuilder))
|
||||
->end() // end of widgets/children
|
||||
->end() // end of widgets
|
||||
->end() // end of root/children
|
||||
->end() // end of root
|
||||
;
|
||||
|
||||
|
||||
return $treeBuilder;
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
#Chill\MainBundle\DependencyInjection\ChillMainExtension.php
|
||||
|
||||
namespace Chill\MainBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\Config\FileLocator;
|
||||
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
|
||||
use Symfony\Component\DependencyInjection\Loader;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
|
||||
use Chill\MainBundle\DependencyInjection\Configuration;
|
||||
|
||||
/**
|
||||
* This class load config for chillMainExtension.
|
||||
*/
|
||||
class ChillMainExtension extends Extension implements Widget\HasWidgetFactoriesExtensionInterface
|
||||
{
|
||||
/**
|
||||
* widget factory
|
||||
*
|
||||
* @var WidgetFactoryInterface[]
|
||||
*/
|
||||
protected $widgetFactories = array();
|
||||
|
||||
public function addWidgetFactory(WidgetFactoryInterface $factory)
|
||||
{
|
||||
$this->widgetFactories[] = $factory;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return WidgetFactoryInterface[]
|
||||
*/
|
||||
public function getWidgetFactories()
|
||||
{
|
||||
return $this->widgetFactories;
|
||||
}
|
||||
|
||||
public function load(array $configs, ContainerBuilder $container)
|
||||
{
|
||||
// configuration for main bundle
|
||||
$configuration = $this->getConfiguration($configs, $container);
|
||||
$config = $this->processConfiguration($configuration, $configs);
|
||||
|
||||
// add the key 'widget' without the key 'enable'
|
||||
$container->setParameter('chill_main.widgets',
|
||||
array('homepage' => $config['widgets']['homepage']));
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public function getConfiguration(array $config, ContainerBuilder $container)
|
||||
{
|
||||
return new Configuration($this->widgetFactories, $container);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
# Chill/PersonBundle/Widget/PersonListWidgetFactory
|
||||
|
||||
namespace Chill\PersonBundle\Widget;
|
||||
|
||||
use Chill\MainBundle\DependencyInjection\Widget\Factory\AbstractWidgetFactory;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
|
||||
|
||||
/**
|
||||
* add configuration for the person_list widget.
|
||||
*/
|
||||
class PersonListWidgetFactory extends AbstractWidgetFactory
|
||||
{
|
||||
/*
|
||||
* append the option to the configuration
|
||||
* see http://symfony.com/doc/current/components/config/definition.html
|
||||
*
|
||||
*/
|
||||
public function configureOptions($place, NodeBuilder $node)
|
||||
{
|
||||
$node->booleanNode('only_active')
|
||||
->defaultTrue()
|
||||
->end();
|
||||
$node->integerNode('number_of_items')
|
||||
->defaultValue(50)
|
||||
->end();
|
||||
$node->scalarNode('filtering_class')
|
||||
->defaultNull()
|
||||
->end();
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* return an array with the allowed places where the widget can be rendered
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function getAllowedPlaces()
|
||||
{
|
||||
return array('homepage');
|
||||
}
|
||||
|
||||
/*
|
||||
* return the widget alias
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getWidgetAlias()
|
||||
{
|
||||
return 'person_list';
|
||||
}
|
||||
|
||||
/*
|
||||
* return the service id for the service which will render the widget.
|
||||
*
|
||||
* this service must implements `Chill\MainBundle\Templating\Widget\WidgetInterface`
|
||||
*
|
||||
* the service must exists in the container, and it is not required that the service
|
||||
* has the `chill_main` tag.
|
||||
*/
|
||||
public function getServiceId(ContainerBuilder $containerBuilder, $place, $order, array $config)
|
||||
{
|
||||
return 'chill_person.widget.person_list';
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
# Chill/PersonBundle/Widget/PersonListWidget.php
|
||||
|
||||
namespace Chill\PersonBundle\Widget;
|
||||
|
||||
use Chill\MainBundle\Templating\Widget\WidgetInterface;
|
||||
use Doctrine\ORM\EntityRepository;
|
||||
use Doctrine\ORM\Query\Expr;
|
||||
use Doctrine\DBAL\Types\Type;
|
||||
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
|
||||
use Chill\PersonBundle\Security\Authorization\PersonVoter;
|
||||
use Symfony\Component\Security\Core\Role\Role;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
|
||||
/**
|
||||
* add a widget with person list.
|
||||
*
|
||||
* The configuration is defined by `PersonListWidgetFactory`
|
||||
*/
|
||||
class PersonListWidget implements WidgetInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* Repository for persons
|
||||
*
|
||||
* @var EntityRepository
|
||||
*/
|
||||
protected $personRepository;
|
||||
|
||||
/**
|
||||
* The entity manager
|
||||
*
|
||||
* @var EntityManager
|
||||
*/
|
||||
protected $entityManager;
|
||||
|
||||
/**
|
||||
* the authorization helper
|
||||
*
|
||||
* @var AuthorizationHelper;
|
||||
*/
|
||||
protected $authorizationHelper;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var TokenStorage
|
||||
*/
|
||||
protected $tokenStorage;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var UserInterface
|
||||
*/
|
||||
protected $user;
|
||||
|
||||
public function __construct(
|
||||
EntityRepository $personRepostory,
|
||||
EntityManager $em,
|
||||
AuthorizationHelper $authorizationHelper,
|
||||
TokenStorage $tokenStorage
|
||||
) {
|
||||
$this->personRepository = $personRepostory;
|
||||
$this->authorizationHelper = $authorizationHelper;
|
||||
$this->tokenStorage = $tokenStorage;
|
||||
$this->entityManager = $em;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param type $place
|
||||
* @param array $context
|
||||
* @param array $config
|
||||
* @return string
|
||||
*/
|
||||
public function render(\Twig_Environment $env, $place, array $context, array $config)
|
||||
{
|
||||
$qb = $this->personRepository
|
||||
->createQueryBuilder('person');
|
||||
|
||||
// show only the person from the authorized centers
|
||||
$and = $qb->expr()->andX();
|
||||
$centers = $this->authorizationHelper
|
||||
->getReachableCenters($this->getUser(), new Role(PersonVoter::SEE));
|
||||
$and->add($qb->expr()->in('person.center', ':centers'));
|
||||
$qb->setParameter('centers', $centers);
|
||||
|
||||
|
||||
// add the "only active" where clause
|
||||
if ($config['only_active'] === true) {
|
||||
$qb->join('person.accompanyingPeriods', 'ap');
|
||||
$or = new Expr\Orx();
|
||||
// add the case where closingDate IS NULL
|
||||
$andWhenClosingDateIsNull = new Expr\Andx();
|
||||
$andWhenClosingDateIsNull->add((new Expr())->isNull('ap.closingDate'));
|
||||
$andWhenClosingDateIsNull->add((new Expr())->gte(':now', 'ap.openingDate'));
|
||||
$or->add($andWhenClosingDateIsNull);
|
||||
// add the case when now is between opening date and closing date
|
||||
$or->add(
|
||||
(new Expr())->between(':now', 'ap.openingDate', 'ap.closingDate')
|
||||
);
|
||||
$and->add($or);
|
||||
$qb->setParameter('now', new \DateTime(), Type::DATE);
|
||||
}
|
||||
|
||||
// adding the where clause to the query
|
||||
$qb->where($and);
|
||||
|
||||
$qb->setFirstResult(0)->setMaxResults($config['number_of_items']);
|
||||
|
||||
$persons = $qb->getQuery()->getResult();
|
||||
|
||||
return $env->render(
|
||||
'ChillPersonBundle:Widget:homepage_person_list.html.twig',
|
||||
array('persons' => $persons)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return UserInterface
|
||||
*/
|
||||
private function getUser()
|
||||
{
|
||||
// return a user
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
# Chill/PersonBundle/DependencyInjection/ChillPersonExtension.php
|
||||
|
||||
namespace Chill\PersonBundle\DependencyInjection;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\Config\FileLocator;
|
||||
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
|
||||
use Symfony\Component\DependencyInjection\Loader;
|
||||
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
|
||||
use Chill\MainBundle\DependencyInjection\MissingBundleException;
|
||||
use Chill\PersonBundle\Security\Authorization\PersonVoter;
|
||||
|
||||
/**
|
||||
* This is the class that loads and manages your bundle configuration
|
||||
*
|
||||
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
|
||||
*/
|
||||
class ChillPersonExtension extends Extension implements PrependExtensionInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function load(array $configs, ContainerBuilder $container)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* Add a widget "add a person" on the homepage, automatically
|
||||
*
|
||||
* @param \Chill\PersonBundle\DependencyInjection\containerBuilder $container
|
||||
*/
|
||||
public function prepend(ContainerBuilder $container)
|
||||
{
|
||||
$container->prependExtensionConfig('chill_main', array(
|
||||
'widgets' => array(
|
||||
'homepage' => array(
|
||||
array(
|
||||
'widget_alias' => 'add_person',
|
||||
'order' => 2
|
||||
)
|
||||
)
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user