Zada1100
Zada1100

Reputation: 41

Odoo 8 open treeview from wizard

I have a wizard that research and add the result to a table and I created a treeview that read the items in this table. I want my wizard to open that treeview once the research is done but I can't find a way to redirect to a specific view from python. Anyone have an idea?

My module is called sale_recherche_client_produit

All my files are at the root of my project folder

My main python file (sale_recherche_client_produit_wizard.py)

# -*- coding: utf-8 -*-
from openerp import models, fields, api, tools, exceptions
from openerp.exceptions import Warning
import math, json, urllib


class SaleRechercheClientProduitWizard(models.TransientModel):
    _name = "sale.order.line.search"

products = fields.Many2one("product.template", string="Meubles", required=True)
lieu = fields.Char(string="Lieu", required=False)
distance = fields.Selection([
    ('10', "10km"),
    ('50', "50km"),
    ('100', "100km"),
    ('aucune', "Aucune limite"),
], default='50',string="Distance", required=True)

@api.one
def recherche(self):
    lieu = self.lieu
    distance = self.distance
    products = self.products

    clients = self.env["res.partner"].search([['is_company', '=', True], ['customer', '=', True]])
    clients_proches = []

    if (distance=="aucune"):
        for client in clients:
            clients_proches.append(client)
    else:
        if lieu :
            coordonees = geo_find(lieu)
            if coordonees:
                lieu_latitude, lieu_longitude = coordonees
            else:
                raise Warning('Veuillez entrer une adresse valide')
        else:
            raise Warning('Veuillez entrer une adresse')

        for client in clients:
            if client.partner_latitude and client.partner_longitude and (calculate_distance(client.partner_latitude, client.partner_longitude, lieu_latitude, lieu_longitude)) <= float(distance):
                clients_proches.append(client)


    if clients_proches:
        order_lines = []
        for client in clients_proches:
            lines = self.env["sale.order.line"].search([['order_partner_id', '=', client.id]])
            if lines:
                for line in lines:
                    if line.product_id.id == products.id:
                        order_lines.append(line)
    else:
        raise Warning('Aucun résultat')

    if order_lines:
        self.env.cr.execute("DELETE FROM sale_order_line_result;")
        for order_line in order_lines:
            self.env["sale.order.line.result"].create({'sale_line_id': order_line.id})

        self.ensure_one()
        treeview_id = self.env.ref('sale_recherche_client_produit.sale_recherche_client_produit_tree_view').id

        return {
            'name': 'Résultats de la recherche',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'sale.order.line.result',
            'views': [(treeview_id, 'tree')],
            'view_id': treeview_id,
            'target': 'current',
        }
    else:
        raise Warning('Aucun résultat')


# Pour trouver la distance entre deux latitudes/longitudes
# explications de l'algorithme sur ce site
# http://www.movable-type.co.uk/scripts/latlong.html

def calculate_distance(lat1, lon1, lat2, lon2):
R = 6371e3
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
deltaPhi = math.radians(lat2-lat1)
deltaLambda = math.radians(lon2-lon1)
a = math.sin(deltaPhi/2) * math.sin(deltaPhi/2) + math.cos(phi1) * math.cos(phi2) * math.sin(deltaLambda/2) * math.sin(deltaLambda/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = (R * c) / 1000
return d


def geo_find(addr):
    url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&key=AIzaSyAIX_OUi6dbQFMzxxvCfMtMiXG3nZBUV4I&address='
    url += urllib.quote(addr.encode('utf8'))

try:
    result = json.load(urllib.urlopen(url))
except Exception, e:
    return 'Network error, Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).' + e
if result['status'] != 'OK':
    return None

try:
    geo = result['results'][0]['geometry']['location']
    return float(geo['lat']), float(geo['lng'])
except (KeyError, ValueError):
    return None

The xml file that goes with the main python file (sale_recherche_client_produit_wizard.xml)

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>

        <record model="ir.ui.view" id="sale_recherche_client_produit_wizard_form">
            <field name="name">sale.recherche.client.produit.form</field>
            <field name="model">sale.order.line.search</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="Rechercher" version="8.0">
                    <p> Veuillez choisir une région et un produit. </p>
                    <group>
                        <field name="products"/>
                    </group>
                    <group>
                        <field name="lieu" />
                        <field name="distance"/>
                    </group>
                    <button string="Rechercher" type="object" name="recherche"/>
                    <button string="Annuler" class="oe_highlight" special="cancel"/>
                </form>
            </field>
        </record>

        <record id="action_sale_recherche_client_produit" model="ir.actions.act_window">
                <field name="name">Recherche de clients</field>
                <field name="res_model">sale.order.line.search</field>
                <field name="view_type">form</field>
                <field name="view_id" ref="sale_recherche_client_produit_wizard_form"/>
                <field name="multi">True</field>
                <field name="target">new</field>
        </record>

        <menuitem action="action_sale_recherche_client_produit" id="menu_sale_recherche_client_produit" name="Recherche clients produits" parent="base.menu_sales"/>

    </data>
</openerp>

The treeview I want to open (sale_recherche_client_produit_tree.xml)

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <record id="sale_recherche_client_produit_tree_view" model="ir.ui.view">
            <field name="name">sale.recherche.client.produit.tree</field>
            <field name="model">sale.order.line.result</field>
            <field name="type">tree</field>
            <field eval="7" name="priority"/>
            <field name="arch" type="xml">
                <tree string="Recherche">
                    <field name="client" string="Client"/>
                    <field name="ville" string="Ville"/>
                    <field name="produit" string="Produit"/>
                    <field name="qty" string="Quantité"/>
                    <field name="date" string="Date"/>
                </tree>
            </field>
        </record>
    </data>
</openerp>

Upvotes: 3

Views: 3429

Answers (1)

Suppose there is one button in wizard when you click on that button it will open tree view of particular model.

In wizard button should looks like,

<button class="oe_inline oe_stat_button" name="open_tree_view"  type="object" icon="fa-pencil"> Open Tree View
</button>

And in py method should looks like,

@api.multi
def open_tree_view(self):
    self.ensure_one()
    treeview_id = self.env.ref('external_id_of_treeview').id
    return {
        'name': 'Title',
        'type': 'ir.actions.act_window',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'model.name',
        'views': [(treeview_id, 'tree')            
        'target': 'current',
        'domain' : [('id','in',search_ids)],
        ### in domain pass ids if you want to show only filter data else it will display all data of that model.
    }

Upvotes: 5

Related Questions