0

I'm developing a telegram bot and I'm using a Drupal site to manage data. From my bot php code I create some nodes like this:

$url = "/entity/node?_format=hal_json"; 
    foreach($obj['pratiche'] as $nid){
        $pratiche[] = ["target_id" => $nid];
    }
    $opt = [
        'headers' => self::getHead(),
        'body' => json_encode([
                'type' => 'presentazione',
                'title' => [ [ 'value' => 'User ' . $obj['telegram_id'] ] ],
                'body' => [ [ 'value' => $obj['body'] ] ],
                'field_anno_di_nascita' => [ [ 'value' => $obj['nascita'] ] ],
                'field_pratiche' => [ [ 'value' =>$pratiche ] ],
          ])
    ];

    $response = $this->client->request('POST', $url , $opt);

As you can see field_pratiche is a node relation field and can have multiple values inserted like an array of ["target_id" => $tid] arrays. The creation is fine.

When I try to edit this node I do something like:

 $url = "/node/".$nid."?_format=hal_json"; 
    $editObj = [ 'type' => 'presentazione' ];

    if(array_key_exists('nascita', $obj)){
        $editObj['field_anno_di_nascita'] = [ [ 'value' => $obj['nascita'] ] ];
    }

    if(array_key_exists('presentazione', $obj)){
        $editObj['body'] =  [ [ 'value' => $obj['presentazione'] ] ];
    }

    if(array_key_exists('pratiche', $obj)){
        foreach($obj['pratiche'] as $p){
            $pratiche[] = ["target_id" => $p];
        } 
        $editObj['field_pratiche'] = [ [ 'value' => $pratiche] ];
    }

    $opt = [
        'headers' => self::getHead(),
        'body' => json_encode($editObj)
    ];
   $response = $this->client->request('PATCH', $url , $opt);

Using the same structure edit of 'field_pratiche' fail. After call edit I can find the new values in the other fields but an empty one for field_pratiche.

How can I achieve this ? How can I edit this multiple node relationship field ?

1 Answer 1

1

The keys of arrays are the column names in the database. Most simple fields like integers or numbers just have one value column. Entity references don't have a value, but a target_id column instead.

Your (multi-value)1 $pratiche already is an (array of)1 arrays with target_id as key, so the value key is superfluent and incorrect [ [ 'value' => $pratiche] ].

Instead simply assign $editObj['field_pratiche'] = $pratiche; directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.