ai_upgrade_assistant-0.2.0-alpha2/src/Form/ForumTopicForm.php

src/Form/ForumTopicForm.php
<?php

namespace Drupal\ai_upgrade_assistant\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\ai_upgrade_assistant\Service\CommunityLearningService;
use Drupal\Core\Messenger\MessengerInterface;

/**
 * Form for creating and editing forum topics.
 */
class ForumTopicForm extends FormBase {

  /**
   * The community learning service.
   *
   * @var \Drupal\ai_upgrade_assistant\Service\CommunityLearningService
   */
  protected $communityLearningService;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new ForumTopicForm.
   *
   * @param \Drupal\ai_upgrade_assistant\Service\CommunityLearningService $community_learning_service
   *   The community learning service.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   */
  public function __construct(
    CommunityLearningService $community_learning_service,
    AccountProxyInterface $current_user,
    MessengerInterface $messenger
  ) {
    $this->communityLearningService = $community_learning_service;
    $this->currentUser = $current_user;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('ai_upgrade_assistant.community_learning'),
      $container->get('current_user'),
      $container->get('messenger')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ai_upgrade_assistant_forum_topic_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $topic_id = NULL) {
    // Load existing topic if editing
    $topic = NULL;
    if ($topic_id) {
      $topic = $this->communityLearningService->getForumTopics(['id' => $topic_id])[0] ?? NULL;
      if (!$topic) {
        throw new NotFoundHttpException();
      }
    }

    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#required' => TRUE,
      '#maxlength' => 255,
      '#default_value' => $topic ? $topic->title : '',
    ];

    $form['content'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Content'),
      '#required' => TRUE,
      '#format' => 'full_html',
      '#default_value' => $topic ? $topic->content : '',
    ];

    $form['tags'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Tags'),
      '#description' => $this->t('Comma-separated list of tags'),
      '#default_value' => $topic ? implode(', ', json_decode($topic->tags)) : '',
    ];

    $form['attachments'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Attachments'),
      '#upload_location' => 'public://ai_upgrade_assistant/forum',
      '#multiple' => TRUE,
      '#description' => $this->t('Allowed file types: txt, pdf, zip, tar.gz'),
      '#upload_validators' => [
        'file_validate_extensions' => ['txt pdf zip tar gz'],
        'file_validate_size' => [25 * 1024 * 1024],
      ],
      '#default_value' => $topic ? json_decode($topic->attachments) : [],
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $topic ? $this->t('Update Topic') : $this->t('Create Topic'),
    ];

    if ($topic) {
      $form['topic_id'] = [
        '#type' => 'hidden',
        '#value' => $topic_id,
      ];
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate tags format
    $tags = $form_state->getValue('tags');
    if ($tags) {
      $tags = array_map('trim', explode(',', $tags));
      foreach ($tags as $tag) {
        if (strlen($tag) > 32) {
          $form_state->setErrorByName('tags', $this->t('Tags must be no longer than 32 characters.'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Prepare tags
    $tags = [];
    if ($form_state->getValue('tags')) {
      $tags = array_map('trim', explode(',', $form_state->getValue('tags')));
      $tags = array_filter($tags);
    }

    // Prepare attachments
    $attachments = [];
    if ($files = $form_state->getValue('attachments')) {
      foreach ($files as $fid) {
        if ($file = \Drupal::entityTypeManager()->getStorage('file')->load($fid)) {
          $file->setPermanent();
          $file->save();
          $attachments[] = $fid;
        }
      }
    }

    // Create or update topic
    $topic_data = [
      'title' => $form_state->getValue('title'),
      'content' => $form_state->getValue('content')['value'],
      'tags' => $tags,
      'attachments' => $attachments,
    ];

    if ($topic_id = $form_state->getValue('topic_id')) {
      // Update existing topic
      $this->communityLearningService->updateForumTopic($topic_id, $topic_data);
      $this->messenger->addStatus($this->t('Forum topic updated.'));
    }
    else {
      // Create new topic
      $topic_id = $this->communityLearningService->createForumTopic(
        $topic_data['title'],
        $topic_data['content'],
        $topic_data['tags'],
        $topic_data['attachments']
      );
      $this->messenger->addStatus($this->t('Forum topic created.'));
    }

    // Redirect to the topic page
    $form_state->setRedirect('ai_upgrade_assistant.forum.topic', ['topic_id' => $topic_id]);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc