doc/book/en/devweb/views/primary.rst
changeset 10491 c67bcee93248
parent 10490 76ab3c71aff2
child 10492 68c13e0c0fc5
equal deleted inserted replaced
10490:76ab3c71aff2 10491:c67bcee93248
     1 .. _primary_view:
       
     2 
       
     3 The Primary View
       
     4 -----------------
       
     5 
       
     6 By default, *CubicWeb* provides a view that fits every available
       
     7 entity type. This is the first view you might be interested in
       
     8 modifying. It is also one of the richest and most complex.
       
     9 
       
    10 It is automatically selected on a one line result set containing an
       
    11 entity.
       
    12 
       
    13 It lives in the :mod:`cubicweb.web.views.primary` module.
       
    14 
       
    15 The *primary* view is supposed to render a maximum of informations about the
       
    16 entity.
       
    17 
       
    18 .. _primary_view_layout:
       
    19 
       
    20 Layout
       
    21 ``````
       
    22 
       
    23 The primary view has the following layout.
       
    24 
       
    25 .. image:: ../../images/primaryview_template.png
       
    26 
       
    27 .. _primary_view_configuration:
       
    28 
       
    29 Primary view configuration
       
    30 ``````````````````````````
       
    31 
       
    32 If you want to customize the primary view of an entity, overriding the primary
       
    33 view class may not be necessary. For simple adjustments (attributes or relations
       
    34 display locations and styles), a much simpler way is to use uicfg.
       
    35 
       
    36 Attributes/relations display location
       
    37 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       
    38 
       
    39 In the primary view, there are three sections where attributes and
       
    40 relations can be displayed (represented in pink in the image above):
       
    41 
       
    42 * 'attributes'
       
    43 * 'relations'
       
    44 * 'sideboxes'
       
    45 
       
    46 **Attributes** can only be displayed in the attributes section (default
       
    47   behavior). They can also be hidden. By default, attributes of type `Password`
       
    48   and `Bytes` are hidden.
       
    49 
       
    50 For instance, to hide the ``title`` attribute of the ``Blog`` entity:
       
    51 
       
    52 .. sourcecode:: python
       
    53 
       
    54    from cubicweb.web.views import uicfg
       
    55    uicfg.primaryview_section.tag_attribute(('Blog', 'title'), 'hidden')
       
    56 
       
    57 **Relations** can be either displayed in one of the three sections or hidden.
       
    58 
       
    59 For relations, there are two methods:
       
    60 
       
    61 * ``tag_object_of`` for modifying the primary view of the object
       
    62 * ``tag_subject_of`` for modifying the primary view of the subject
       
    63 
       
    64 These two methods take two arguments:
       
    65 
       
    66 * a triplet ``(subject, relation_name, object)``, where subject or object can be replaced with ``'*'``
       
    67 * the section name or ``hidden``
       
    68 
       
    69 .. sourcecode:: python
       
    70 
       
    71    pv_section = uicfg.primaryview_section
       
    72    # hide every relation `entry_of` in the `Blog` primary view
       
    73    pv_section.tag_object_of(('*', 'entry_of', 'Blog'), 'hidden')
       
    74 
       
    75    # display `entry_of` relations in the `relations`
       
    76    # section in the `BlogEntry` primary view
       
    77    pv_section.tag_subject_of(('BlogEntry', 'entry_of', '*'), 'relations')
       
    78 
       
    79 
       
    80 Display content
       
    81 ^^^^^^^^^^^^^^^
       
    82 
       
    83 You can use ``primaryview_display_ctrl`` to customize the display of attributes
       
    84 or relations. Values of ``primaryview_display_ctrl`` are dictionaries.
       
    85 
       
    86 
       
    87 Common keys for attributes and relations are:
       
    88 
       
    89 * ``vid``: specifies the regid of the view for displaying the attribute or the relation.
       
    90 
       
    91   If ``vid`` is not specified, the default value depends on the section:
       
    92     * ``attributes`` section: 'reledit' view
       
    93     * ``relations`` section: 'autolimited' view
       
    94     * ``sideboxes`` section: 'sidebox' view
       
    95 
       
    96 * ``order``: int used to control order within a section. When not specified,
       
    97   automatically set according to order in which tags are added.
       
    98 
       
    99 * ``label``: label for the relations section or side box
       
   100 
       
   101 * ``showlabel``: boolean telling whether the label is displayed
       
   102 
       
   103 .. sourcecode:: python
       
   104 
       
   105    # let us remind the schema of a blog entry
       
   106    class BlogEntry(EntityType):
       
   107        title = String(required=True, fulltextindexed=True, maxsize=256)
       
   108        publish_date = Date(default='TODAY')
       
   109        content = String(required=True, fulltextindexed=True)
       
   110        entry_of = SubjectRelation('Blog', cardinality='?*')
       
   111 
       
   112    # now, we want to show attributes
       
   113    # with an order different from that in the schema definition
       
   114    view_ctrl = uicfg.primaryview_display_ctrl
       
   115    for index, attr in enumerate('title', 'content', 'publish_date'):
       
   116        view_ctrl.tag_attribute(('BlogEntry', attr), {'order': index})
       
   117 
       
   118 By default, relations displayed in the 'relations' section are being displayed by
       
   119 the 'autolimited' view. This view will use comma separated values, or list view
       
   120 and/or limit your rset if there is too much items in it (and generate the "view
       
   121 all" link in this case).
       
   122 
       
   123 You can control this view by setting the following values in the
       
   124 `primaryview_display_ctrl` relation tag:
       
   125 
       
   126 * `limit`, maximum number of entities to display. The value of the
       
   127   'navigation.related-limit'  cwproperty is used by default (which is 8 by default).
       
   128   If None, no limit.
       
   129 
       
   130 * `use_list_limit`, number of entities until which they should be display as a list
       
   131   (eg using the 'list' view). Below that limit, the 'csv' view is used. If None,
       
   132   display using 'csv' anyway.
       
   133 
       
   134 * `subvid`, the subview identifier (eg view that should be used of each item in the
       
   135   list)
       
   136 
       
   137 Notice you can also use the `filter` key to set up a callback taking the related
       
   138 result set as argument and returning it filtered, to do some arbitrary filtering
       
   139 that can't be done using rql for instance.
       
   140 
       
   141 
       
   142 .. sourcecode:: python
       
   143 
       
   144    pv_section = uicfg.primaryview_section
       
   145    # in `CWUser` primary view, display `created_by`
       
   146    # relations in relations section
       
   147    pv_section.tag_object_of(('*', 'created_by', 'CWUser'), 'relations')
       
   148 
       
   149    # display this relation as a list, sets the label,
       
   150    # limit the number of results and filters on comments
       
   151    def filter_comment(rset):
       
   152        return rset.filtered_rset(lambda x: x.e_schema == 'Comment')
       
   153    pv_ctrl = uicfg.primaryview_display_ctrl
       
   154    pv_ctrl.tag_object_of(('*', 'created_by', 'CWUser'),
       
   155                          {'vid': 'list', 'label': _('latest comment(s):'),
       
   156                           'limit': True,
       
   157                           'filter': filter_comment})
       
   158 
       
   159 .. warning:: with the ``primaryview_display_ctrl`` rtag, the subject or the
       
   160    object of the relation is ignored for respectively ``tag_object_of`` or
       
   161    ``tag_subject_of``. To avoid warnings during execution, they should be set to
       
   162    ``'*'``.
       
   163 
       
   164 
       
   165 .. automodule:: cubicweb.web.views.primary
       
   166 
       
   167 
       
   168 Example of customization and creation
       
   169 `````````````````````````````````````
       
   170 
       
   171 We'll show you now an example of a ``primary`` view and how to customize it.
       
   172 
       
   173 If you want to change the way a ``BlogEntry`` is displayed, just
       
   174 override the method ``cell_call()`` of the view ``primary`` in
       
   175 ``BlogDemo/views.py``.
       
   176 
       
   177 .. sourcecode:: python
       
   178 
       
   179    from cubicweb.predicates import is_instance
       
   180    from cubicweb.web.views.primary import Primaryview
       
   181 
       
   182    class BlogEntryPrimaryView(PrimaryView):
       
   183        __select__ = PrimaryView.__select__ & is_instance('BlogEntry')
       
   184 
       
   185        def render_entity_attributes(self, entity):
       
   186            self.w(u'<p>published on %s</p>' %
       
   187                   entity.publish_date.strftime('%Y-%m-%d'))
       
   188            super(BlogEntryPrimaryView, self).render_entity_attributes(entity)
       
   189 
       
   190 
       
   191 The above source code defines a new primary view for
       
   192 ``BlogEntry``. The `__reid__` class attribute is not repeated there since it
       
   193 is inherited through the `primary.PrimaryView` class.
       
   194 
       
   195 The selector for this view chains the selector of the inherited class
       
   196 with its own specific criterion.
       
   197 
       
   198 The view method ``self.w()`` is used to output data. Here `lines
       
   199 08-09` output HTML for the publication date of the entry.
       
   200 
       
   201 .. image:: ../../images/lax-book_09-new-view-blogentry_en.png
       
   202    :alt: blog entries now look much nicer
       
   203 
       
   204 Let us now improve the primary view of a blog
       
   205 
       
   206 .. sourcecode:: python
       
   207 
       
   208  from logilab.mtconverter import xml_escape
       
   209  from cubicweb.predicates import is_instance, one_line_rset
       
   210  from cubicweb.web.views.primary import Primaryview
       
   211 
       
   212  class BlogPrimaryView(PrimaryView):
       
   213      __regid__ = 'primary'
       
   214      __select__ = PrimaryView.__select__ & is_instance('Blog')
       
   215      rql = 'Any BE ORDERBY D DESC WHERE BE entry_of B, BE publish_date D, B eid %(b)s'
       
   216 
       
   217      def render_entity_relations(self, entity):
       
   218          rset = self._cw.execute(self.rql, {'b' : entity.eid})
       
   219          for entry in rset.entities():
       
   220              self.w(u'<p>%s</p>' % entry.view('inblogcontext'))
       
   221 
       
   222  class BlogEntryInBlogView(EntityView):
       
   223      __regid__ = 'inblogcontext'
       
   224      __select__ = is_instance('BlogEntry')
       
   225 
       
   226      def cell_call(self, row, col):
       
   227          entity = self.cw_rset.get_entity(row, col)
       
   228          self.w(u'<a href="%s" title="%s">%s</a>' %
       
   229                 entity.absolute_url(),
       
   230                 xml_escape(entity.content[:50]),
       
   231                 xml_escape(entity.description))
       
   232 
       
   233 This happens in two places. First we override the
       
   234 render_entity_relations method of a Blog's primary view. Here we want
       
   235 to display our blog entries in a custom way.
       
   236 
       
   237 At `line 10`, a simple request is made to build a result set with all
       
   238 the entities linked to the current ``Blog`` entity by the relationship
       
   239 ``entry_of``. The part of the framework handling the request knows
       
   240 about the schema and infers that such entities have to be of the
       
   241 ``BlogEntry`` kind and retrieves them (in the prescribed publish_date
       
   242 order).
       
   243 
       
   244 The request returns a selection of data called a result set. Result
       
   245 set objects have an .entities() method returning a generator on
       
   246 requested entities (going transparently through the `ORM` layer).
       
   247 
       
   248 At `line 13` the view 'inblogcontext' is applied to each blog entry to
       
   249 output HTML. (Note that the 'inblogcontext' view is not defined
       
   250 whatsoever in *CubicWeb*. You are absolutely free to define whole view
       
   251 families.) We juste arrange to wrap each blogentry output in a 'p'
       
   252 html element.
       
   253 
       
   254 Next, we define the 'inblogcontext' view. This is NOT a primary view,
       
   255 with its well-defined sections (title, metadata, attribtues,
       
   256 relations/boxes). All a basic view has to define is cell_call.
       
   257 
       
   258 Since views are applied to result sets which can be tables of data, we
       
   259 have to recover the entity from its (row,col)-coordinates (`line
       
   260 20`). Then we can spit some HTML.
       
   261 
       
   262 .. warning::
       
   263 
       
   264   Be careful: all strings manipulated in *CubicWeb* are actually
       
   265   unicode strings. While web browsers are usually tolerant to
       
   266   incoherent encodings they are being served, we should not abuse
       
   267   it. Hence we have to properly escape our data. The xml_escape()
       
   268   function has to be used to safely fill (X)HTML elements from Python
       
   269   unicode strings.
       
   270 
       
   271 Assuming we added entries to the blog titled `MyLife`, displaying it
       
   272 now allows to read its description and all its entries.
       
   273 
       
   274 .. image:: ../../images/lax-book_10-blog-with-two-entries_en.png
       
   275    :alt: a blog and all its entries
       
   276