View source
<?php
namespace Drupal\user_badges\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityManagerInterface;
class UserBadgesListBuilder extends ControllerBase implements FormInterface {
protected $formBuilder;
protected $user;
protected $storageController;
public function __construct(FormBuilderInterface $form_builder, EntityTypeManagerInterface $entity_type_manager) {
$this->formBuilder = $form_builder;
$this->storageController = $entity_type_manager
->getStorage('badge');
}
public static function create(ContainerInterface $container) {
return new static($container
->get('form_builder'), $container
->get('entity_type.manager'));
}
public function badgesListing(UserInterface $user) {
$this->user = $user;
return $this->formBuilder
->getForm($this);
}
public function getFormId() {
return 'badge_display_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$user = $this->user;
$form['badge'] = array(
'#type' => 'table',
'#header' => array(
t('Label'),
t('Weight'),
t('Select Weight'),
),
'#empty' => t('There are no badges yet'),
);
$field_item_list = $user
->get('field_user_badges');
foreach ($field_item_list
->filterEmptyItems() as $index => $item) {
$badge = $item
->get('entity')
->getValue();
$form['badge'][$badge
->id()]['#attributes']['class'][] = 'draggable';
$form['badge'][$badge
->id()]['#weight'] = $badge
->getBadgeWeight();
$form['badge'][$badge
->id()]['label'] = array(
'#plain_text' => $badge
->label(),
);
$form['badge'][$badge
->id()]['id'] = array(
'#plain_text' => $badge
->getBadgeWeight(),
);
$form['badge'][$badge
->id()]['weight'] = array(
'#type' => 'weight',
'#title' => t('Weight for @title', array(
'@title' => $badge
->label(),
)),
'#title_display' => 'invisible',
'#default_value' => $badge
->getBadgeWeight(),
'#attributes' => array(
'class' => array(
'user-badges-order-weight',
),
),
);
}
$form['badge']['#tabledrag'][] = array(
'action' => 'order',
'relationship' => 'sibling',
'group' => 'user-badges-order-weight',
);
$form['actions'] = array(
'#tree' => FALSE,
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this
->t('Save Badges'),
'#button_type' => 'primary',
);
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$badge_ids = array_keys($form_state
->getValue('badge'));
$user = $this->user;
$user
->set('field_user_badges', $badge_ids);
$user
->save();
}
}