Score:0

Why is this hook implementation not working?

cn flag

I am new to custom modules and hooks and i am trying to connect to a sharepoint site i created to upload pictures of a content i have into sharepoint instead of drupal's file system. My issue is not actually with all this, the initial function sharepoint_file_upload_form_alter isn't working. I added the die(); function to test if the function is being called but i was able to add content normally. I made sure the names of the content types and then the name of the function and module are the same so i have no idea what else to check. Can anyone help please? Thank you.

<?php

use Symfony\Component\HttpClient\HttpClient;

/**
 * Implements hook_form_alter().
 */
function sharepoint_file_upload_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'album_photo_evenements_node_form') {
    die();
    $form['field_images_album']['#element_validate'][] = 'sharepoint_file_upload_image_upload_validate';
  }
}

function sharepoint_file_upload_image_upload_validate($element, &$form_state, $form) {
  // Loop through each file uploaded in the field_images_album field.
  foreach ($element['#value'] as $key => $value) {
    if (!empty($value['fid'])) {
      $file = file_load($value['fid']);
      if ($file) {
        // Get the file contents.
        $file_contents = file_get_contents($file->getFileUri());

        // Upload the file to SharePoint.
        $url = upload_file_to_sharepoint($file->getFilename(), $file_contents);

        if ($url) {
          // Save the file URL to the field_images_album field.
          $form_state['values']['field_images_album'][LANGUAGE_NONE][$key]['value'] = $url;
        }
        else {
          drupal_set_message(t('Error uploading file to SharePoint.'), 'error');
        }

        // Delete the uploaded file.
        file_delete($file);
      }
      else {
        drupal_set_message(t('Error loading file.'), 'error');
      }
    }
  }
}

/**
 * Uploads a file to SharePoint.
 */
function upload_file_to_sharepoint($file_name, $file_contents) {
  // Get the SharePoint authentication token.
  $digest_value = get_sharepoint_auth_token();

  if ($digest_value) {
    // Set the SharePoint REST API endpoint.
    $url = "https://testusjedu.sharepoint.com/sites/usjnet_Production/_api/web/Lists(guid'4a3b0d0c-0ec0-40f2-89db-e355a778f639')/Items";

    // Set the necessary headers.
    $headers = [
        'Authorization' => 'Bearer ' . $digest_value,
        'Accept' => 'application/json;odata=verbose',
        'Content-Type' => 'application/json;odata=verbose',
    ];

    // Set the request payload.
    $payload = [
        'Title' => 'New Image',
        'Image' => [
            '__metadata' => [
                'type' => 'SP.FieldUrlValue',
            ],
            'Description' => 'Image description',
            'Url' => '',
        ],
    ];

    // Make the request to SharePoint.
    $client = HttpClient::create();
    $response = $client->request('POST', $url, [
        'headers' => $headers,
        'json' => $payload,
    ]);

    if ($response->getStatusCode() == 201) {
        $responseData = json_decode($response->getContent(), true);
        $uploadedImageUrl = $responseData['d']['Url'];
        return $uploadedImageUrl;
    } else {
        return FALSE;
    }
  }
  else {
    return FALSE;
  }
}

/**
 * Gets the SharePoint authentication token.
 */
function get_sharepoint_auth_token() {
  // Replace these values with your actual Azure app and SharePoint details
  $clientId = '#######';
  $clientSecret = '#######';
  $tenantId = '########';
  $resource = "https://testusjedu.sharepoint.com/sites/usjnet_Production/_api/web/Lists(guid'4a3b0d0c-0ec0-40f2-89db-e355a778f639')/Items"; // SharePoint site URL or API endpoint URL

  $tokenEndpoint = sprintf('https://login.microsoftonline.com/%s/oauth2/token', $tenantId);

  $client = HttpClient::create();

  $response = $client->request('POST', $tokenEndpoint, [
    'body' => [
        'grant_type' => 'client_credentials',
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'resource' => $resource,
    ],
  ]);

  $content = $response->getContent();
  $accessToken = json_decode($content, true)['access_token'];

  return $accessToken;
}
id flag
What is the name of the module’s info.yml file? Did you rebuild caches after introducing the hooks? Is the module installed?
Rayan Frem avatar
cn flag
Hello, yes all the above has been done. Module name is sharepoint_file_upload(Folder name, .info.yml file name and .module file name are all the same)
id flag
It is necessary to interview you because there is not enough information in the question to provide a factual answer. Are you certain `album_photo_evenements_node_form` is the correct form identifier?
Rayan Frem avatar
cn flag
The content type has machine name album_photo_evenements As per google aqnd chat gpt the form id is the machine name with _node_form at the end. is this correct?
id flag
https://drupal.stackexchange.com/questions/5802/how-can-i-find-the-form-id-of-a-form
Rayan Frem avatar
cn flag
Thank you, turned out the id should be node_album_photo_evenements_form and that's why it wasn't working. Thank you for your help.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.