Hi, I have a content type with a multiple youtube field type. Now, when I try to programmatically save this field, no matter what I do, It remains blank.

I do it this way:

$node->field_youtube_video[$node->language][]['value']="http://www.youtube.com/watch?v=jRPDvD4kiI8";
node_save( $node );

It creates all the fields, but the value is empty.

Thanks in advance! Diego

Comments

Pasqualle’s picture

try:

$node->field_youtube_video[LANGUAGE_NONE][0]['video_id'] = 'jRPDvD4kiI8';
node_save( $node );
John Pitcairn’s picture

You probably shouldn't assume a particular language, so that should really be:

<?php
$node->field_your_field_name[$node->language][0]['video_id'] = 'jRPDvD4kiI8';
node_save($node);
Pasqualle’s picture

But afaik field language is not the same as node language. Those are 2 different things.
So for a non translatable field the language should be LANGUAGE_NONE

guschilds’s picture

Status: Active » Fixed

If you use Devel to examine a YouTube field created via GUI, you'll notice there is 'input' alongside 'video_id'.

'input' is the full URL given to the field. The 'video_id' is then derived from that by the module.

To properly save a YouTube field programmatically, you should really also provide the full URL for 'input':

$node->field_youtube_video[LANGUAGE_NONE][0]['video_id'] = 'jRPDvD4kiI8';
$node->field_youtube_video[LANGUAGE_NONE][0]['input'] = 'http://www.youtube.com/watch?v=jRPDvD4kiI8';

'input' is important to have because:

  • it is used by youtube_field_is_empty()
  • we are also implementing the ability to link to the YouTube video from a thumbnail in #1423616: image link and that needs 'input' to work.
  • it will be the field's default value when the node is edited via the GUI, so that field will appear as blank otherwise and editing it will be awkward.

If you were batch saving nodes and only had the 'video_id', you could construct an appropriate 'input' by simply adding 'http://www.youtube.com/watch?v=' before the 'video_id'.

We will add this information to the README when it is created for #1616690: Create a README.txt explaining valid YouTube URLS.

As for the language debate, I believe @Pasqualle is correct in saying that node and field languages are not the same thing and this field is not translatable, therefore I went with his use of LANGUAGE_NONE above.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

gzveri’s picture

Issue summary: View changes

In Drupal8 here's the working code:

$dx = [];
$vidid = youtube_get_video_id($input); 
//ex: $input="https://www.youtube.com/watch?v=fDTT6T_Se6M";
$dx[] = [
  'video_id' => $vidid,
  'input' => 'http://www.youtube.com/watch?v='.$vidid,
];
$node->videofield = $dx;
$node->save();