当前位置:网站首页>Learn how to develop owl components by hand (7): practical use of owl projects

Learn how to develop owl components by hand (7): practical use of owl projects

2022-06-26 13:19:00 Digital China cloud base


One 、 Project background

This time there is a new demand , Ask for in Odoo Add a new... On the menu bar of Switch The toggle button , After switching Tree The data of the view should also pass through Switch Value to filter , Consider the data response and subsequent code optimization , It is not a good way to extend the source code , It happens that our front end is also right OWL There is also a certain introduction , So this time we'll use OWL Let's practice !


Two 、 Page effect and expectation

In the face of Switch Button switching , Page data filtering update .
 Insert picture description here


3、 ... and 、 Implementation steps

1. establish switch Of xml file , With OWL How to write

( notes : Here owl=“1” An integral ):

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
     <t t-name="owl.switchButton" owl="1">
         <div class="switchContainer" style="display: flex; align-items: center;">
            <span> The stock of </span>
            <input type="checkbox" class="switch-button" id="switch-button"/>
            <label for="switch-button" style="margin: 0 5px;"></label>
            <span>PO The stock of </span>
        </div>
     </t>
 </templates>

2. Create the corresponding js file , As a class component Switch Definition

odoo.define('switch_owl', function (require) {
    
    "use strict";
    const {
    Component} = owl;

    class SwitchButton extends Component {
    
        static template="owl.switchButton";
    };
    return SwitchButton
})

3. Reference and instantiate the page to be displayed

Since we need to bind to Tree On view , And filter the data , Then we can ListController Of renderButton method , It also helps us to bind events :

odoo.define('render_switch', function (require) {
    
    "use strict";
    var ListController = require('web.ListController');
    const {
    ComponentWrapper} = require("web.OwlCompatibility");
    var session = require('web.session')
    var framework = require("web.framework");
	//  introduce Switch Of Owl Components 
    var switch_owl = require('switch_owl')
    return ListController.extend({
    
        renderButtons: function () {
    
            let self = this
            this._super.apply(this, arguments);
            if (this.$buttons) {
    
                // this ⾥ Find the button and input field just defined 
                this.$buttons.find('.o_list_export_xlsx').addClass('d-none');
                $('#switch_block').remove()
				//  Add a... Before the menu bar target div To render Switch
                $('.o_menu_systray').css({
    'display': 'flex'}).prepend(`<div id="switch_block" style="display: flex; align-items: center"></div>`)
                $(document).ready(function () {
    
					//  Instantiation Switch +  Rendering 
                    (new ComponentWrapper(self, switch_owl)).mount($('#switch_block')[0]).then(()=>{
    
						//  Yes Switch Bind switch event 
                        $('#switch-button').on('click', self.proxy('switch_func'));
						//  from sessionStorage In order to get Switch The status value is used to check the status after refresh 
                        let switch_check = JSON.parse(window.sessionStorage.getItem('switch_check'))
                        $('#switch-button')[0].checked = switch_check
                    });
                })
            }
        },
        updateButtons: function () {
    
            this.$buttons.find('.o_list_export_xlsx').hide();
            this._super.apply(this, arguments);
        },
		// Switch Check the event 
        switch_func: function (ev){
    
            let self = this
			//  take Switch Cache the value of to sessionStorage in 
            window.sessionStorage.setItem('switch_check', $(ev.target)[0].checked)
			// Page data refresh after switching 
            self.trigger_up('reload')
        }
    });
});

4. Expand basic_model.js Medium search_read Method , Switch Switch Post invocation method :

odoo.define('summary_model', function (require) {
    
    "use strict";
    var BasicModel = require('web.BasicModel');
    return BasicModel.extend({
    
        _searchReadUngroupedList: function (list) {
    
            var self = this;
			//  From the cache Switch value , And put this parameter in context in 
            let switch_check = JSON.parse(window.sessionStorage.getItem('switch_check'))
            if(switch_check){
    
                list.context.information_source = 'PO Notice '
            }else{
    
                list.context.information_source = ' Inventory table '
            }
            var fieldNames = list.getFieldNames();
            var prom;
            if (list.__data) {
    
                // the data have already been fetched (alonside the groups by the
                // call to 'web_read_group'), so we can bypass the search_read
                prom = Promise.resolve(list.__data);
            } else {
    
                prom = this._rpc({
    
                    route: '/web/dataset/search_read',
                    model: list.model,
                    fields: fieldNames,
                    context: _.extend({
    }, list.getContext(), {
    bin_size: true}),
                    domain: list.domain || [],
                    limit: list.limit,
                    offset: list.loadMoreOffset + list.offset,
                    orderBy: list.orderedBy,
                });
            }
            return prom.then(function (result) {
    
                delete list.__data;
                list.count = result.length;
                var ids = _.pluck(result.records, 'id');
                var data = _.map(result.records, function (record) {
    
                    var dataPoint = self._makeDataPoint({
    
                        context: list.context,
                        data: record,
                        fields: list.fields,
                        fieldsInfo: list.fieldsInfo,
                        modelName: list.model,
                        parentID: list.id,
                        viewType: list.viewType,
                    });

                    // add many2one records
                    self._parseServerData(fieldNames, dataPoint, dataPoint.data);
                    return dataPoint.id;
                });
                if (list.loadMoreOffset) {
    
                    list.data = list.data.concat(data);
                    list.res_ids = list.res_ids.concat(ids);
                } else {
    
                    list.data = data;
                    list.res_ids = ids;
                }
                self._updateParentResIDs(list);
                return list;
            });
        },
    });
});

5. Introduce the above two js file , Binding in ListView On , And bound to the corresponding Tree Of js_class

odoo.define('summary_predict_button', function (require) {
    
    "use strict";
    var ListView = require('web.ListView');
    var viewRegistry = require('web.view_registry');
    var dom = require('web.dom');
    var render_switch = require('render_switch')
    var ListRenderer = require('web.ListRenderer');
    var SumPredictModel = require('summary_model')
    var SumPredictRenderer = ListRenderer.extend({
    
        _renderSelector: function (tag, disableInput) {
    
            var $content = dom.renderCheckbox();
            if (disableInput) {
    
                $content.find("input[type='checkbox']").prop('disabled', disableInput);
            }
            return
        },
    })
    var BiConListView = ListView.extend({
    
        config: _.extend({
    }, ListView.prototype.config, {
    
            Controller: render_switch,
            Renderer: SumPredictRenderer,
            Model: SumPredictModel
        }),
        _extractParamsFromAction: function (action) {
    
            var params = this._super.apply(this, arguments);
            params.hasActionMenus = false;
            return params;
        },
    });
    // this ⾥⽤ To register views written BiConListView, The first ⼀ The first string is the registered name, which should be called according to the registered name ⽤ View 
    viewRegistry.add('summary_predict_button', BiConListView);
    return BiConListView;
});

6. rewrite menu Click event

Here you can see Switch The button has been rendered on the page , And when switching , Values can be passed to search_read Interface , And then filter the data , But there will be a jump to other modules Switch, This is what we don't want , So be right menu Click the event to rewrite :

odoo.define('menu_toggle', function (require) {
    
    const Menu = require("web.Menu");
    Menu.include({
    
        events: _.extend(
            {
    
                'click a': '_onDropdownClicked',
            },
            Menu.prototype.events
        ),
        _onDropdownClicked: function (ev) {
    
            let current_menu_xmlid = $(ev.currentTarget).attr('data-menu-xmlid')
            if(current_menu_xmlid == undefined) return
			//  need Switch Button page 
            let menu_data_arr = ['xc_spare_parts.spare_parts_root_menu',
                'xc_spare_parts.aggregate_forecasts_menu','xc_spare_parts.base_data_menu','xc_spare_parts.material_logic_menu',
                'xc_spare_parts.bom_total_table_menu','xc_spare_parts.prepare_materials_menu','xc_spare_parts.week_estimates_views_menu', 'xc_spare_parts.alternative_prepare_materials_menu']
            var menu_flag = menu_data_arr.some(function (item) {
    
                return item == current_menu_xmlid
            })
			//  To identify with Switch Show and hide 
            if(menu_flag){
    
                setTimeout( function() {
     $('#switch_block').show()}, 1000);
            }else{
    
                setTimeout( function() {
     $('#switch_block').hide()}, 1000);
            }
        },
    });
})

7. Enclosed Switch The style of

.switch-button {
    
   display: none;
   /* Hide form elements */
}

.switch-button+label {
    
   /*+ Selector selection follows “+” The first element of the left selector */
   display: inline-block;
   position: relative;
   transition: all .3s;
   width: 60px;
   height: 30px;
   border: 1px solid #999;
   border-radius: 15px;
   background-color: #ccc;
}

.switch-button:checked+label {
    
   /* Select the style after the form ,:checked Express checkbox Status after being selected */
   background-color: #169bd5;
}

.switch-button+label::before {
    
   /* Generate a button using pseudo elements */
   content: '';
   display: block;
   height: 25px;
   width: 25px;
   position: absolute;
   border-radius: 25px;
   left: 2px;
   top: 2px;
   background-color: #fff;
   box-shadow: 0 1px 3px rgba(0, 0, 0, .4);
   transition: all .3s;
}

.switch-button:checked+label::before {
    
   /*checkbox The style of the button when selected */
   left: 32px;
   transition: all .2s linear;
}

8. Update complete

take js and xml The documents are in template and __manifest__ I quote , After updating the module, it is finished .


Four 、 Conclusion

This is a OWL An attempt and application in actual development , Welcome to discuss with us any good ideas and suggestions ~

原网站

版权声明
本文为[Digital China cloud base]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261139331494.html