How to use the "Select Listing Media " field in a custom content type

Dear support,

I would like to know how/if I can use the “Select Listing Media” in a custom content type to choose between an Image selection field and a CDS selection field, like it is possible for a Landing page.

Kind regards,
Katarina Sigerud

Hello Katarina,

Yes you can use the Select Listing Media in order to select which media type to upload. I will provide an example below to make it simpler.

Let’s say that you have a custom content type called “News”. This content type has the following fields:

  • CDS media (field of type CERN CDS Media)
  • Local media (local image or video)
  • Select listing media field (select field)

The first thing you need to do is bind the media fields with the select list one. In order to do that:

  1. Visit the manage form display of your content type
  2. Create a group by clicking “Add Group”
  3. Create a group with a related name (ex. Media) and of type Details with the default settings
  4. Place the 3 fields under the newly created group

media

The next step is to set the listing media to change from the one fields to the other whenever you change the value of it. But this needs to be done using a custom module. For this you need:

  1. Create a custom module

  2. Inside the module place the following code snippet:

    function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) 
    {
    if ($form_id == 'id_of_the_edit_form_of_your_content_type_nodes') {
     if (isset( $form['field_listing_media'])) { 
        $form['machine_name_of_cds_field']['#states'] = [
          'visible' => [
              'select[name="machine_name_of_cds_field"]' => ['value' => 'cds']
           ]
        ];
    
        $form['machine_name_of_local_field']['#states'] = [
           'visible' => [
             'select[name="machine_name_of_local_field"]' => ['value' => 'image']
        ]
       ];
      } 
     }
    }
    

Its kinda complicated, so if you need more details let me know.

Kostas