View source
<?php
namespace Drupal\crm_core_contact\Plugin\Action;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
use Drupal\crm_core_contact\Entity\Contact;
use Drupal\relation\Entity\Relation;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Entity\EntityFormBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
class JoinIntoHouseholdAction extends ConfigurableActionBase implements ContainerFactoryPluginInterface {
const RELATION_TYPE_HOUSEHOLD = 'crm_member';
protected $currentUser;
protected $entityFormBuilder;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxy $current_user, EntityFormBuilder $entity_form_builder) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
$this->entityFormBuilder = $entity_form_builder;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'), $container
->get('entity.form_builder'));
}
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $return_as_object ? AccessResult::allowed() : AccessResult::allowed()
->isAllowed();
}
public function executeMultiple(array $objects) {
if (!isset($this->configuration['household'])) {
$this->configuration['household'] = Contact::create([
'type' => 'household',
]);
}
$this->configuration['household']
->setOwnerId($this->currentUser
->id());
$this->configuration['household']
->save();
foreach ($objects as $member) {
$endpoints = array(
0 => array(
'entity_type' => $member
->getEntityTypeId(),
'entity_id' => $member
->id(),
),
1 => array(
'entity_type' => 'crm_core_contact',
'entity_id' => $this->configuration['household']
->id(),
),
);
$relation = Relation::create([
'relation_type' => self::RELATION_TYPE_HOUSEHOLD,
'endpoints' => $endpoints,
]);
$relation
->save();
}
}
public function execute($object = NULL) {
$this
->executeMultiple(array(
$object,
));
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$household = Contact::create([
'type' => 'household',
'name' => 'Fam. Smith',
]);
return $this->entityFormBuilder
->getForm($household);
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['household'] = $form_state
->getFormObject()
->getEntity();
}
}