Search code examples
phparraysodooxml-rpcmany-to-one

How to get value from many2one type using php


I want to get partner data which is have information id, name, and salesperson_id where the 'salesperson_id' is many2one type (contains id and name). Here's my code :

    <?php
    // Login information
    $url = 'localhost';
    $url_auth = $url . '/xmlrp/common';
    $url_exec = $url . '/xmlrpc/object';

    $db = 'testing';
    $username = 'odoo';
    $password = 'odoo';

    // Ripcord can be cloned from https://github.com/poef/ripcord
    require_once('ripcord/ripcord.php');

    // Login
    $common = ripcord::client("$url/xmlrpc/common");
    //$common = ripcord::client($url_auth);
    $uid = $common->authenticate($db, $username, $password, array());

    //print("<p>Your current user id is '${uid}'</p>");

    $models = ripcord::client($url_exec);

    $customer = $models->execute_kw(
        $db,
        $uid,
        $password,
        'res.partner',
        'search_read', 
        array( // Search domain
            array(
                array('is_company', '=', true), // Query condition
                array('customer', '=', true)) // Query condition
            ),
        array('fields'=> array('name', 'salesperson_id'))
    );

    print("<p><strong>Found customers:</strong><br/>");
    foreach ($customer as $customers){
        print("${customers[id]}
               ${customers[name]}
               {$customers[salesperson_id][0]}

               <br/>");
        }
    print("</p>");
?>

It will show :

Found customers:
1234 CHLOE 12
1235 DRY MART 13
1236 SEEYOU 14
1237 ED. COMP 15

SOLVED!!


Solution

  • I don't know if you want to print the ID or the name of the Salesperson. But the problem with your code throwing a 500 Server Error is an IndexError. When you do $customers[salesperson_id][1], it will fail on the first one because the user does not have a salesperson. Thus $customers[salesperson_id] is not an array but a Boolean, and trying to access any Index of it will throw an error.

    I'm not good with PHP, so I'm just going to point out the answer :

    • $customers[salesperson_id][0] is the ID of the salesperson, $customers[salesperson_id][1] is its name.
    • if the customer does not have a salesperson, $customers[salesperson_id] will have false as value.

    So the solution :

    • Check if $customers[salesperson_id] is not false
    • print $customers[salesperson_id][0] or $customers[salesperson_id][1] if $customers[salesperson_id] is not false