Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/IoC.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/IoC.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/IoC"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/IoC"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@@ -0,0 +1,243 @@
# -*- coding: utf-8 -*-
#
# IoC documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 29 01:43:00 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sensio.sphinx.refinclude', 'sensio.sphinx.configurationblock', 'sensio.sphinx.phpcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Sonata ~ CoreBundle'
copyright = u'2010-2015, Thomas Rabaix'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
#version = '0.0.1'
# The full version, including alpha/beta/rc tags.
#release = '0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
import sphinx_rtd_theme
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'doc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# ('index', 'PythonElement.tex', u'Python Documentation',
# u'Thomas Rabaix', 'manual'),
#]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
#(source start file, name, description, authors, manual section).
#man_pages = [
# ('index', 'ioc', u'IoC Documentation',
# [u'Thomas Rabaix'], 1)
#]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
#texinfo_documents = [
# ('index', 'IoC', u'IoC Documentation',
# u'Thomas Rabaix', 'IoC', 'One line description of project.',
# 'Miscellaneous'),
#]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

View File

@@ -0,0 +1,23 @@
Core Bundle
===========
The ``SonataCoreBundle`` provided defaults elements required by the different Sonata's Bundles.
.. toctree::
:caption: Reference Guide
:name: reference-guide
:maxdepth: 1
:numbered:
reference/installation
reference/form_types
reference/status_helper
reference/flash_messages
reference/twig_helpers
reference/doctrine_base_manager
reference/serialization
reference/api
reference/conditional_validation
reference/command
reference/testing

View File

@@ -0,0 +1,30 @@
.. index::
double: Api; Definition
Api
===
The bundle comes with a handy ``FormHelper::removeField`` method which can be used to remove form's fields
if the related submitted data is not provided. The Form Component's default behavior is to set ``null`` if a form
field is defined but no data submitted for this particular field. This is quite annoying while building an API and the
client only sent partial data to update an entity.
.. code-block:: php
<?php
$category = $id ? $this->getCategory($id) : null;
$form = $this->formFactory->createNamed(null, 'sonata_classification_api_form_category', $category, array(
'csrf_protection' => false
));
FormHelper::removeFields($request->request->all(), $form);
$form->bind($request);
if ($form->isValid()) {
// ...
}
The call need to be done before the ``bind`` function as you cannot manipulate the form after the binding.

View File

@@ -0,0 +1,26 @@
Command
=======
You can create a dump file with entity schema information. For each entity, you will get
table name and the mapping between fields and column names (related entities fields won't be displayed).
.. code-block:: bash
Usage:
sonata:core:dump-doctrine-metadata -r "/ProductBundle/" -f /tmp/dump.json
Options:
--filename (-f) If filename is specified, result will be dumped into this file under json format.
--entity-name (-E) If entity-name is set, dump will only contain the specified entity and all its extended classes.
--regex (-r) If regex is set, dump will only contain entities which name match the pattern.
--help (-h) Display this help message.
--quiet (-q) Do not output any message.
--verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug.
--version (-V) Display this application version.
--ansi Force ANSI output.
--no-ansi Disable ANSI output.
--no-interaction (-n) Do not ask any interactive question.
--shell (-s) Launch the shell.
--process-isolation Launch commands from shell as a separate process.
--env (-e) The Environment name. (default: "dev")
--no-debug Switches off debug mode.

View File

@@ -0,0 +1,157 @@
Inline Validation
=================
The inline validation is about delegating model validation to a dedicated service.
The current validation implementation built in the Symfony framework is very powerful
as it allows to declare validation on a : class, field and getter. However these declarations
can take a while to code for complex rules. As rules must be a set of a ``Constraint``
and a ``Validator`` instances.
The inline validation tries to provide a nice solution by introducing an ``ErrorElement``
object. The object can be used to check assertions against the model :
.. code-block:: php
<?php
$errorElement
->with('settings.url')
->assertNotNull(array())
->assertNotBlank()
->end()
->with('settings.title')
->assertNotNull(array())
->assertNotBlank()
// for minimum length constraint
->assertLength(array('min' => 50))
// for maximum length constraint
->assertLength(array('max' => 100))
->addViolation('ho yeah!')
->end()
;
// ...
if (/* complex rules */) {
$errorElement
->with('value')
->addViolation('Fail to check the complex rules')
->end()
;
}
// ...
/* conditional validation */
if ($this->getSubject()->getState() == Post::STATUS_ONLINE) {
$errorElement
->with('enabled')
->assertNotNull()
->assertTrue()
->end()
;
}
.. note::
This solution relies on the validator component so validation defined through
the validator component will be used.
.. tip::
You can also use ``$errorElement->addConstraint(new \Symfony\Component\Validator\Constraints\NotBlank())``
instead of calling ``assertNotBlank()``.
You can also use ``$errorElement->addConstraint(new \Symfony\Component\Validator\Constraints\Length(array('min'=>5, 'max'=>100))``
instead of calling ``assertLength()``.
Using this Validator
--------------------
Add the ``InlineConstraint`` class constraint to your bundle's validation configuration, for example:
.. configuration-block::
.. code-block:: xml
<!-- src/Application/Sonata/PageBundle/Resources/config/validation.xml -->
<?xml version="1.0" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="Application\Sonata\PageBundle\Entity\Block">
<constraint name="Sonata\CoreBundle\Validator\Constraints\InlineConstraint">
<option name="service">sonata.page.cms.page</option>
<option name="method">validateBlock</option>
</constraint>
</class>
</constraint-mapping>
.. code-block:: yaml
# src/Application/Sonata/PageBundle/Resources/config/validation.yml
Application\Sonata\PageBundle\Entity\Block:
constraints:
- Sonata\CoreBundle\Validator\Constraints\InlineConstraint:
service: sonata.page.cms.page
method: validateBlock
There are two important options:
- ``service``: the service where the validation method is defined
- ``method``: the service's method to call
.. note::
If the ``service`` or ``method`` are not string, you will need to re-attach the validation on each request. Set
the ``serializingWarning`` option to ``true`` once it is done.
The method must accept two arguments:
- ``ErrorElement``: the instance where assertion can be checked
- ``value``: the object instance
Example from the ``SonataPageBundle``
-------------------------------------
.. code-block:: php
<?php
namespace Sonata\PageBundle\Block;
use Sonata\PageBundle\Model\PageInterface;
use Sonata\CoreBundle\Validator\ErrorElement;
use Sonata\BlockBundle\Block\BaseBlockService;
use Sonata\BlockBundle\Model\BlockInterface;
class RssBlockService extends BaseBlockService
{
// ...
public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
{
$errorElement
->with('settings.url')
->assertNotNull(array())
->assertNotBlank()
->end()
->with('settings.title')
->assertNotNull(array())
->assertNotBlank()
// for minimum length constraint
->assertLength(array('min' => 50))
// for maximum length constraint
->assertLength(array('max' => 100))
->addViolation('ho yeah!')
->end()
;
}
// ...
}

View File

@@ -0,0 +1,27 @@
.. index::
single: Doctrine
single: Managers
Doctrine base entity manager
============================
The bundle comes with an abstract class for your entities and documents managers ``Sonata\CoreBundle\Model\BaseEntityManager``,``Sonata\CoreBundle\Model\BaseDocumentManager`` and ``Sonata\CoreBundle\Model\BasePHPCRManager``.
Use it in your managers
-----------------------
You just have to extend ``Sonata\CoreBundle\Model\BaseEntityManager``, ``Sonata\CoreBundle\Model\BaseDocumentManager`` or ``Sonata\CoreBundle\Model\BasePHPCRManager`` in your managers, for instance:
.. code-block:: php
<?php
// src/AppBundle/Entity/ProductManager.php
namespace AppBundle\Entity;
use Sonata\CoreBundle\Model\BaseEntityManager;
class ProductManager extends BaseEntityManager
{
// ...
}

View File

@@ -0,0 +1,67 @@
.. index::
double: Flash Message; Definition
Flash Messages
==============
The bundle comes with a ``FlashManager`` to handle some *session flash messages types* that you can specify in the configuration
to be returned as a ``success``, ``warning`` or ``error`` type (or even all your custom types you want to add).
Additionally, you can also add a ``css_class`` section for each flash messages that will be displayed on rendering.
Configuration
-------------
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
sonata_core:
flashmessage:
success:
types:
- { type: my_custom_bundle_success, domain: MyCustomBundle }
- { type: my_other_bundle_success, domain: MyOtherBundle }
warning:
types:
- { type: my_custom_bundle_warning, domain: MyCustomBundle }
- { type: my_other_bundle_warning } # if nothing is specified, sets SonataCoreBundle by default
error:
css_class: danger # optionally, a CSS class can be defined
types:
- { type: my_custom_bundle, domain: MyCustomBundle }
custom_type: # You can add custom types too
types:
- { type: custom_bundle_type, domain: MyCustomBundle }
You can specify multiple *flash messages types* you want to manage here.
Usage
-----
To use this feature in your PHP classes/controllers, you can use for example:
.. code-block:: php
<?php
$flashManager = $this->get('sonata.core.flashmessage.manager');
$messages = $flashManager->get('success');
To use this feature in your templates, simply include the following template (with an optional domain parameter):
.. code-block:: jinja
{% include 'SonataCoreBundle:FlashMessage:render.html.twig' %}
Please note that if necessary, you can also specify a translation domain to override configuration here:
.. code-block:: jinja
{% include 'SonataCoreBundle:FlashMessage:render.html.twig' with {domain: 'MyCustomBundle'} %}

View File

@@ -0,0 +1,530 @@
.. index::
double: Form Type; Definition
Form Types
==========
The bundle comes with some handy form types.
Symfony3 Supports
-----------------
In order to help the migration path toward Symfony3, the bundle restores the Symfony2.X behavior of string code usage for the form type declaration.
Each bundles can register a mapping with Symfony3 boot.
.. code-block:: php
<?php
namespace Sonata\AdminBundle;
use Sonata\CoreBundle\Form\FormHelper;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SonataAdminBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container)
{
$this->registerFormMapping();
}
/**
* {@inheritdoc}
*/
public function boot()
{
$this->registerFormMapping();
}
/**
* Register form mapping information
*/
public function registerFormMapping()
{
FormHelper::registerFormTypeMapping(array(
'sonata_type_admin' => 'Sonata\AdminBundle\Form\Type\AdminType', // the form mapping
));
FormHelper::registerFormExtensionMapping('choice', array( // the extended mapping for the choice type
'sonata.admin.form.extension.choice',
));
}
}
You can either alter your bundle to configure these mappings or you can add the mapping as configuration settings. Values provided in configuration will overwrite default values:
.. code-block: yaml
sonata_core:
form:
mapping:
enabled: true # (default value)
type:
sonata_type_admin: Sonata\AdminBundle\Form\Type\AdminType
extension:
choice:
- sonata.admin.form.extension.choice
If you are lazy, you can get the mapping with the command:
.. code-block: yaml
app/console sonata:core:form-mapping -f yaml|php
DoctrineORMSerializationType
----------------------------
This form type reads ``JMSSerializer`` serialization class metadata and uses ``Doctrine`` ORM entity metadata to generate form fields and correct types.
All you have to do is to define a form type service for each entity for which you want to use a form type, like this:
.. configuration-block::
.. code-block:: xml
<service id="my.custom.form.type.comment" class="Sonata\CoreBundle\Form\Type\DoctrineORMSerializationType">
<tag name="form.type" alias="my_custom_form_type_comment" />
<argument type="service" id="jms_serializer.metadata_factory" />
<argument type="service" id="doctrine" />
<argument>my_custom_form_type_comment</argument>
<argument>AppBundle\Entity\Comment</argument>
<argument>a_serialization_group</argument>
</service>
The service definition should contain the following arguments:
* The JMSSerializer metadata factory,
* The Doctrine ORM entity manager,
* The form type name,
* The entity class name for which you want to build form,
* The serialization group you want serialization fields have.
.. warning::
``DoctrineORMSerializationType`` cannot be used directly with Symfony3.0, you need to extends the class ``BaseDoctrineORMSerializationType``
with an empty class to have an unique FQCN.
sonata_type_immutable_array
---------------------------
The ``Immutable Array`` allows you to edit an array property by defining a type per key.
The type has a ``keys`` parameter which contains the definition for each key.
A definition is either a ``FormBuilder`` instance, or an array with 3 options:
* key name,
* type: a type name or a ``FormType`` instance,
* related type parameters: please refer to the related form documentation.
Let's say a ``Page`` has options property with some fixed key-value pairs.
Each value has a different type: `integer`, `url`, or `string` for instance.
.. code-block:: php
<?php
// src/AppBundle/Entity/Page.php
class Page
{
protected $options = array(
'ttl' => 1,
'redirect' => ''
);
public function setOptions(array $options)
{
$this->options = $options;
}
public function getOptions()
{
return $this->options;
}
}
Now, the property can be edited by setting a type for each type:
.. code-block:: php
<?php
// src/AppBundle/Admin/PageAdmin.php
class PageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('options', 'sonata_type_immutable_array', array(
'keys' => array(
array('ttl', 'text', array('required' => false)),
array('redirect', 'url', array('required' => true)),
)
))
// ...
;
}
// ...
}
sonata_type_boolean
-------------------
The ``boolean`` type is a specialized ``ChoiceType``, where the list of choices is locked to *yes* and *no*.
Note that for backward compatibility reasons, it will set your value to *1* for *yes* and to *2* for *no*.
If you want to map to a boolean value, just set the option ``transform`` to true. For instance, you need to do so when mapping to a doctrine boolean.
sonata_type_translatable_choice
-------------------------------
The translatable type is a specialized ``ChoiceType`` where the choices values are translated with the Symfony Translator component.
The type has one extra parameter:
* ``catalogue``: the catalogue name to translate the value.
.. code-block:: php
<?php
// src/AppBundle/Entity/Delivery.php
class Delivery
{
public static function getStatusList()
{
return array(
self::STATUS_OPEN => 'status_open',
self::STATUS_PENDING => 'status_pending',
self::STATUS_VALIDATED => 'status_validated',
self::STATUS_CANCELLED => 'status_cancelled',
self::STATUS_ERROR => 'status_error',
self::STATUS_STOPPED => 'status_stopped',
);
}
// ...
}
.. code-block:: php
<?php
// src/AppBundle/Admin/DeliveryAdmin.php
class DeliveryAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('deliveryStatus', 'sonata_type_translatable_choice', array(
'choices' => Delivery::getStatusList(),
'catalogue' => 'SonataOrderBundle'
))
// ...
;
}
// ...
}
.. note::
For more information, you can check the official `ChoiceType documentation`_ .
sonata_type_collection
----------------------
The ``Collection Type`` is meant to handle creation and editing of model
collections. Rows can be added and deleted, and your model abstraction layer may
allow you to edit fields inline. You can use ``type_options`` to pass values
to the underlying forms.
.. code-block:: php
<?php
// src/AppBundle/Entity/ProductAdmin.php
class ProductAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('sales', 'sonata_type_collection', array(
// Prevents the "Delete" option from being displayed
'type_options' => array('delete' => false)
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position',
))
// ...
;
}
// ...
}
The available options (which can be passed as a third parameter to ``FormMapper::add()``) are:
btn_add and btn_catalogue:
The label on the ``add`` button can be customized
with this parameters. Setting it to ``false`` will hide the
corresponding button. You can also specify a custom translation catalogue
for this label, which defaults to ``SonataAdminBundle``.
type_options:
This array is passed to the underlying forms.
pre_bind_data_callback:
This closure will be executed during the preBind method (``FormEvent::PRE_BIND`` | ``FormEvent::PRE_SUBMIT``)
to build the data given to the form based on the value retrieved. Use this if you need to generate your forms based
on the submitted data.
**TIP**: A jQuery event is fired after a row has been added (``sonata-admin-append-form-element``).
You can listen to this event to trigger custom javascript (eg: add a calendar widget to a newly added date field)
StatusType
----------
The ``StatusType`` is not available as a service. However, you can use it to declare your own type to render a choice of status.
Let's say, you have a ``Delivery::getStatusList`` method which returns a list of status. Now, you want to create a form type to expose those values.
.. code-block:: php
<?php
// src/AppBundle/Entity/Delivery.php
class Delivery
{
public static function getStatusList()
{
return array(
self::STATUS_OPEN => 'status_open',
self::STATUS_PENDING => 'status_pending',
self::STATUS_VALIDATED => 'status_validated',
self::STATUS_CANCELLED => 'status_cancelled',
self::STATUS_ERROR => 'status_error',
self::STATUS_STOPPED => 'status_stopped',
);
}
}
This can be done by declaring a new service:
.. configuration-block::
.. code-block:: xml
<service id="sonata.order.form.status_type" class="Sonata\CoreBundle\Form\Type\StatusType">
<tag name="form.type" alias="sonata_order_status" />
<argument>%sonata.order.order.class%</argument>
<argument>getStatusList</argument>
<argument>sonata_order_status</argument>
</service>
And the type can now be used:
.. code-block:: php
<?php
// src/AppBundle/Admin/DeliveryAdmin.php
class DeliveryAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('deliveryStatus', 'sonata_order_status')
// ...
;
}
}
.. warning::
``StatusType`` cannot be used directly with Symfony3.0, you need to extends the class ``BaseStatusType``
with an empty class to have an unique FQCN.
sonata_type_date_picker and sonata_type_datetime_picker
-------------------------------------------------------
Those types integrate `Eonasdan's Bootstrap datetimepicker`_ into a Symfony form.
They both are available as services, and inherit from ``date`` and ``datetime`` default form types.
.. note::
These form types require you to have bootstrap and jquery assets available in your project.
They will allow you to have a JS date picker onto your form fields as follows:
.. image:: ../images/datepicker.png
In order to use them, you'll need to perform a bit of setup:
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
twig:
form_themes:
- 'SonataCoreBundle:Form:datepicker.html.twig'
In your layout, you'll need to add the assets dependencies (feel free to adapt this to your needs, for instance to use with assetic):
.. code-block:: html
<head>
<!-- ... -->
<script type="text/javascript" src="path_to_jquery.min.js"></script>
<script type="text/javascript" src="/bundles/sonatacore/vendor/moment/min/moment-with-locales.min.js"></script>
<script type="text/javascript" src="path_to_bootstrap.min.js"></script>
<script type="text/javascript" src="/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="path_to_bootstrap.min.css" />
<link rel="stylesheet" href="/bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css" />
</head>
Finally, in your form, you may use the form type as follows:
.. code-block:: php
<?php
// src/AppBundle/Admin/PageAdmin.php
class PageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('publicationDateStart', 'sonata_type_datetime_picker')
// or sonata_type_date_picker if you don't need the time
->add('publicationDateStart', 'sonata_type_date_picker')
// ...
;
}
}
Many of the `standard date picker options`_ are available by adding options with a ``dp_`` prefix:
.. code-block:: php
<?php
// src/AppBundle/Admin/PageAdmin.php
class PageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('publicationDateStart', 'sonata_type_datetime_picker', array(
'dp_side_by_side' => true,
'dp_use_current' => false,
'dp_use_seconds' => false,
'dp_collapse' => true,
'dp_calendar_weeks' => false,
'dp_view_mode' => 'days',
'dp_min_view_mode' => 'days',
))
// or sonata_type_date_picker if you don't need the time
->add('publicationDateStart', 'sonata_type_date_picker', array(
'dp_use_current' => false,
))
;
}
}
If you look in the classes ``DateTimePickerType.php`` and ``BasePickerType.php`` you can see all the currently available options.
In addition to these standard options, there is also the option ``datepicker_use_button`` which, when used, will change the widget so that the datepicker icon is not shown and the pop-up datepicker is invoked simply by clicking on the date input.
sonata_type_date_range_picker and sonata_type_datetime_range_picker
-------------------------------------------------------------------
``sonata_type_date_range_picker`` and ``sonata_type_datetime_range_picker`` extends the basic range form field types (``sonata_type_date_range`` and ``sonata_type_datetime_range``).
You can use them if you need datetime picker in datetime range filters.
Example with ``doctrine_orm_date_range`` filter:
.. code-block:: php
<?php
// src/AppBundle/Admin/PostAdmin.php
class PostAdmin extends Admin
{
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('createdAt', 'doctrine_orm_date_range', array(
'field_type' => 'sonata_type_date_range_picker',
))
// ...
;
}
// ...
}
sonata_type_color
------------------------
This is HTML5 input type color.
.. image:: ../images/color.png
In order to use it, you'll need to perform a bit of setup:
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
twig:
form_themes:
- 'SonataCoreBundle:Form:color.html.twig'
Finally, in your form, you may use the form type as follows:
.. code-block:: php
<?php
// src/AppBundle/Admin/PageAdmin.php
class PageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('color', 'sonata_type_color')
// ...
;
}
// ...
}
.. _`ChoiceType documentation`: http://symfony.com/doc/current/reference/forms/types/choice.html
.. _`Eonasdan's Bootstrap datetimepicker`: https://github.com/Eonasdan/bootstrap-datetimepicker
.. _`standard date picker options`: http://eonasdan.github.io/bootstrap-datetimepicker/#options

View File

@@ -0,0 +1,60 @@
.. index::
single: Installation
Installation
============
The easiest way to install ``SonataCoreBundle`` is to require it with Composer:
.. code-block:: bash
$ php composer.phar require sonata-project/core-bundle
Alternatively, you could add a dependency into your ``composer.json`` file directly.
Now, enable the bundle in the kernel:
.. code-block:: php
<?php
// app/AppKernel.php
public function registerBundles()
{
return array(
// ...
new Sonata\CoreBundle\SonataCoreBundle(),
// ...
);
}
Configuration
=============
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
sonata_core: ~
When using bootstrap, some widgets need to be wrapped in a special ``div`` element
depending on whether you are using the standard style for your forms or the
horizontal style.
If you are using the horizontal style, you will need to configure the
corresponding configuration node accordingly:
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
sonata_core:
form_type: horizontal
Please note that if you are using the admin bundle, this is actually optional:
The core bundle extension will detect if the configuration node that deals with
the form style in the admin bundle is set and will configure the core bundle for you.

View File

@@ -0,0 +1,61 @@
.. index::
double: Custom Handlers; Definition
Serialization
=============
Custom handlers
---------------
The bundle comes with a ``BaseSerializerHandler`` to let you customize your serialized entities;
this handler is used to serialize/deserialize an entity to/from its id within the defaults
formats ('json', 'xml', 'yml').
The serializer default formats are configurable. You can change them from the configuration file.
.. code-block:: yaml
sonata_core:
serializer:
formats: ['json', 'xml', 'yml']
You can set these formats to a different array or you can add another format to these formats by using
``BaseSerializerHandler`` methods ``setFormats`` and ``addFormat``
You are free to create your own handler for your specific needs.
Just override ``Sonata\CoreBundle\Serializer\BaseSerializerHandler`` to create a `JMS Serializer` handler.
You can define your handler like this:
.. code-block:: xml
<service id="app.serializer.post" class="AppBundle\Serializer\PostSerializerHandler">
<tag name="jms_serializer.subscribing_handler" />
<argument type="service" id="app.manager.post" />
</service>
To call your handler, you can use a custom type used by `JMS Serializer`, like this:
.. code-block:: xml
<property name="post" serialized-name="entity_id" type="post_type" />
And your handler need to specify the type name:
.. code-block:: php
<?php
// src/AppBundle/Serializer/PostSerializerHandler.php
namespace AppBundle\Serializer;
use Sonata\CoreBundle\Serializer\BaseSerializerHandler;
class PostSerializerHandler extends BaseSerializerHandler
{
public static function getType()
{
return 'post_type';
}
}

View File

@@ -0,0 +1,53 @@
.. index::
double: Twig Status Helpers; Definition
Twig status helper
==================
The bundle comes with a `Twig` helper allowing you to generate CSS class names, depending on an entity field.
Define a service
----------------
Each service you want to define must implement the ``Sonata\CoreBundle\Component\Status\StatusClassRendererInterface`` interface. For instance:
.. code-block:: php
<?php
namespace Sonata\Component\Order;
use Sonata\CoreBundle\Component\Status\StatusClassRendererInterface;
class OrderStatusRenderer implements StatusClassRendererInterface
{
public function handlesObject($object, $statusName = null)
{
// Logic validating if the render is applicable for the given object
}
public function getStatusClass($object, $statusName = null, $default = "")
{
// Label to render
}
}
Now that we have defined our service, we will add it using the ``sonata.status.renderer`` tag, just as follow:
.. code-block:: xml
<service id="sonata.order.status.renderer" class="Sonata\Component\Order\OrderStatusRenderer">
<tag name="sonata.status.renderer" />
</service>
.. code-block:: yaml
services:
sonata.order.status.renderer:
class: Sonata\Component\Order\OrderStatusRenderer
tags:
- { name: sonata.status.renderer }
Use the service
---------------
You can now call your helper in your twig views using the following code: ``{{ my_object|sonata_status_class(status_name, 'default_value') }}``

View File

@@ -0,0 +1,30 @@
.. index::
double: Test Widgets; Definition
Testing
=======
Test Widgets
~~~~~~~~~~~~
You can write unit tests for twig form rendering with the following code.
.. code-block:: php
use Sonata\CoreBundle\Test\AbstractWidgetTestCase;
class CustomTest extends AbstractWidgetTestCase
{
public function testAcmeWidget()
{
$options = array(
'foo' => 'bar',
);
$form = $this->factory->create('Acme\Form\CustomType', null, $options);
$html = $this->renderWidget($form->createView());
$expected = '<input foo="bar" />';
$this->assertContains($expected, $this->cleanHtmlWhitespace($html));
}
}

View File

@@ -0,0 +1,31 @@
.. index::
double: Twig Helpers; Definition
Twig Helpers
============
sonata_slugify (deprecated)
---------------------------
This filter is deprecated. Install `cocur/slugify` and enable `CocurSlugifyBundle` https://github.com/cocur/slugify#symfony2 for using `slugify` filter.
Create a slug from a string:
.. code-block:: jinja
{{ "my string"|sonata_slugify }}
Results in ::
my-string
sonata_flashmessages_get and sonata_flashmessages_types
-------------------------------------------------------
See :doc:`flash_messages` for more information.
sonata_urlsafeid
----------------
Gets the identifiers of the object as a string that is safe to use in an url.

View File

@@ -0,0 +1,3 @@
Sphinx
git+https://github.com/fabpot/sphinx-php.git
sphinx_rtd_theme