prepare for merging doc into mono-repository

This commit is contained in:
2021-03-25 17:06:29 +01:00
parent daec8c892c
commit d9759024ef
68 changed files with 0 additions and 0 deletions

View 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);
}

View 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();
}
});

View File

@@ -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'
});

View 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
} ) }}

View 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());
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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';
}
}

View File

@@ -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
}
}

View File

@@ -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
)
)
)
));
}
}