View source
<?php
namespace Drupal\uc_fulfillment\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\uc_order\OrderInterface;
use Drupal\uc_store\Address;
class AddressForm extends FormBase {
public function getFormId() {
return 'uc_fulfillment_address_form';
}
public function buildForm(array $form, FormStateInterface $form_state, array $addresses = [], OrderInterface $uc_order = NULL) {
$form['#attached']['library'][] = 'uc_fulfillment/uc_fulfillment.scripts';
$form['origin'] = [
'#type' => 'fieldset',
'#title' => t('Origin address'),
'#weight' => -2,
];
$form['origin']['pickup_address_select'] = $this
->selectAddress($addresses);
$form['origin']['pickup_address_select']['#weight'] = -2;
$form['origin']['pickup_email'] = [
'#type' => 'email',
'#title' => t('E-mail'),
'#default_value' => uc_store_email(),
'#weight' => -1,
];
$form['origin']['pickup_address'] = [
'#type' => 'uc_address',
'#default_value' => reset($addresses),
'#required' => FALSE,
];
$form['destination'] = [
'#type' => 'fieldset',
'#title' => t('Destination address'),
'#weight' => -1,
];
if ($form_state
->hasValue('delivery_country')) {
$uc_order->delivery_country = $form_state
->getValue('delivery_country');
}
$form['destination']['delivery_email'] = [
'#type' => 'email',
'#title' => t('E-mail'),
'#default_value' => $uc_order
->getEmail(),
'#weight' => -1,
];
$form['destination']['delivery_address'] = [
'#type' => 'uc_address',
'#default_value' => $uc_order
->getAddress('delivery'),
'#required' => FALSE,
'#key_prefix' => 'delivery',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
}
protected function selectAddress(array $addresses = []) {
$quote_config = $this
->config('uc_quote.settings');
$ship_from_address = Address::create($quote_config
->get('ship_from_address'));
if (!in_array($ship_from_address, $addresses)) {
$addresses[] = $ship_from_address;
}
$blank = Address::create([
'first_name' => '',
'last_name' => '',
'company' => '',
'street1' => '',
'street2' => '',
'city' => '',
'postal_code' => '',
'country' => '',
'zone' => '',
'phone' => '',
]);
$options = [
Json::encode($blank) => t('- Reset fields -'),
];
foreach ($addresses as $address) {
$options[Json::encode($address)] = $address
->getCompany() . ' ' . $address
->getStreet1() . ' ' . $address
->getCity();
}
$select = [
'#type' => 'select',
'#title' => t('Saved addresses'),
'#options' => $options,
'#default_value' => Json::encode($addresses[0]),
'#attributes' => [
'onchange' => 'apply_address(\'pickup\', this.value);',
],
];
return $select;
}
}