Odoo 12 Development Essentials
上QQ阅读APP看书,第一时间看更新

Creating the form view

All views are stored in the database, in the ir.ui.view model. To add a view to a module, we declare a <record> element describing the view in an XML file, which is to be loaded into the database when the module is installed.

Add this new views/book_view.xml file to define the form view:

<?xml version="1.0"?> 
<odoo> 
  <record id="view_form_book" model="ir.ui.view"> 
    <field name="name">Book Form</field> 
    <field name="model">library.book</field> 
    <field name="arch" type="xml"> 
      <form string="Book">
        <group>
          <field name="name" /> 
<field name="author_ids" widget="many2many_tags" />
<field name="publisher_id" /> <field name="date_published" />
<field name="isbn" />
<field name="active" />
<field name="image" widget="image" />
</group> </form> </field> </record> </odoo>

The ir.ui.view record has values for three fields: name, model, and arch. Another important element is the record id. It defines an XML ID identifier that can be used for other records to reference it.

The view is for the library.book model and is named Book Form. The name is just for information purpose; it does not have to be unique, but it should allow you to easily identify which record it refers to. In fact, the name can be entirely omitted; in that case, it will be automatically generated from the model name and the view type.

The most important field is arch, as it contains the view definition, highlighted in the previously listed XML code. The <form> tag defines the view type, and it contains the view structure.

In this case, it is the <group> element that contains the fields to be shown in the form.The fields automatically use an appropriate default widget, such as the date-selection widget for date fields. In some cases, we may want to use a different widget. That is the case for author_ids, which is using a widget to display the authors as a list of tags, and the image field, which is using a widget appropriate for handling images. A detailed explanation of view elements is provided in Chapter 10, Backend Views – Design the User Interface.

Remember to add this new file to the data key in the manifest file; otherwise, our module won't know about it and it won't be loaded:

'data': [
'security/library_security.xml',
'security/ir.model.access.csv',
'views/library_menu.xml',
'views/book_view.xml',
],

Remember that, for the changes to be loaded to our Odoo database, a module upgrade is needed. To see the changes in the web client, the form needs to be reloaded. Either click again on the menu option that opens it or reload the browser page (F5 in most browsers).