magento2 – Add attributes to the Order API shipping_address

Okay, after stepping trough some other places, I’ve eventually identified how I can add the attributes to a additional key called extension_attributes inside billing_address. Not exactly what I was looking for, but a good start.

My extension_attributes.xml looks like this now:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="MagentoSalesApiDataOrderAddressExtensionInterface">
        <attribute code="my_attr_1" type="string" />
        <attribute code="my_attr_2" type="string" />
    </extension_attributes>
</config>

Also, I’ve created in my module etc/webapi_rest/di.xml with this content:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MagentoSalesModelOrderRepository">
        <plugin name="order_repository" type="SEECRestApiPluginMagentoSalesModelOrderRepository" disabled="false" sortOrder="200" />
    </type>
</config>

And created this file to attach the data properly:

<?php

namespace SEECRestApiPluginMagentoSalesModel;

use MagentoSalesApiDataOrderInterface;
use MagentoSalesModelOrderRepository as ModelOrderRepository;

class OrderRepository
{

    /**
     * @param ModelOrderRepository $orderRepository
     * @param OrderInterface $order
     * @return OrderInterface
     */
    public function afterGet(
        ModelOrderRepository $orderRepository,
        OrderInterface $order
    ) {
        $billingAddress = $order->getBillingAddress();
        $billingAddressExtensionAttributes = (null !== $billingAddress->getExtensionAttributes())
            ? $billingAddress->getExtensionAttributes()
            : '';

        $billingAddressExtensionAttributes->setMyAttr1($billingAddress->getMyAttr1());
        $billingAddressExtensionAttributes->setMyAttr2($billingAddress->getMyAttr2());

        $billingAddress->setExtensionAttributes($billingAddressExtensionAttributes);

        if (!$order->getIsVirtual()) {
            $shippingAddress = $order->getShippingAddress();
            $shippingAddressExtensionAttributes = (null!== $shippingAddress->getExtensionAttributes())
                ? $shippingAddress->getExtensionAttributes()
                : '';

            $shippingAddressExtensionAttributes->setMyAttr1($shippingAddress->getMyAttr1());
            $shippingAddressExtensionAttributes->setMyAttr2($shippingAddress->getMyAttr2());
            $shippingAddress->setExtensionAttributes($shippingAddressExtensionAttributes);
        }

        return $order;
    }
}

magento2 – magento 2 get folter attributes values in custom api

Hi i created custom API in magento 2 in that i need to implement advance search like store brand,model and year search like this enter image description here

i am able to get brand fileds `

public function getAddtocar($attribute) {

//        echo "sdfkjhsdkjfhsdkjhfkjdshfjkds";

        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $filterableAttributes = $objectManager->getInstance()->get(MagentoCatalogModelLayerCategoryFilterableAttributeList::class);
        $layerResolver = $objectManager->getInstance()->get(MagentoCatalogModelLayerResolver::class);
        $filterList = $objectManager->getInstance()->create(
                MagentoCatalogModelLayerFilterList::class, (
            'filterableAttributes' => $filterableAttributes
                )
        );
        $layer = $layerResolver->get();
        $filters = $filterList->getFilters($layer);
//                    $maxPrice = $layer->getProductCollection();


        $i = 0;
        $values = ();
        $filterAttrs = ();
        foreach ($filters as $filter) {
            $attr_code = (string) $filter->getRequestVar();
            if ($attr_code == $attribute) {
                $attr_label = (string) $filter->getName();
                $items = $filter->getItems(); //Gives all available filter options in that particular filter
                foreach ($items as $item) {

                    $values() = array(
                        "id" => $item->getValue(),
                        "count" => $item->getCount(),
                        "label" => strip_tags($item->getLabel()));
                }
//                $logger->info('Array Log count of values' . print_r($values, true)); // Array Log  
                if (!empty($values) && count($values) > 1) {
                    $filterAttrs() = array(
                        "label" => $attr_label,
                        "options" => $values,
                        "code" => $attr_code);
                }
            }
        }
        $response = ('status' => 'true', 'layeredData' => $filterAttrs);
        echo $json = json_encode($response, JSON_UNESCAPED_UNICODE);
        die();

`by using abouve code i am able to show brand fileds which assigned to products after selection of brand need to get model filed
forexample:: brand->hyundai,lexus,kia once select kia i need to get kia related model can any one suggest how to get like selection based

php – divide the editor text which have html attributes on every 500 th character length for creating text slider

I have to create the text slider , but that text have html attributes also,so supposed i have 1000 char length of text including html attribute and if i am dividing the text on every 500 character the html div tag will also get divide and my text will look like an simple text ,is there any solution ,hope you guyz get understand what im trying to do

                $msg  = $message;
                
                $xyz =  strip_tags($msg);
              
                $lentgh = strlen($xyz);
                
                $noOfDiv = round($lentgh/500);


                for($i = 1 ; $i <= $noOfDiv ;$i++){
                    $startPoint = $prevPoint;
                    $endPoint = $startPoint + 500;
                    $prevPoint = $endPoint;

                    $abc = substr($msg,  $startPoint, $endPoint);
                 

                    echo "<div class='mySlides '>
                        <div class='numbertext'>".$i." / ".$noOfDiv."</div>
                        <div class='message__text__container'>
                            <div class='text'> ".$abc."</div>
                        </div>
                    </div>";
               
                } 

         

normalization – How do I identify functional dependencies and normalize a table based on the attributes?

I’m having trouble identifying the combination of attributes which make up Functional Dependencies(FDs) of a particular table. While I understand how Normalization process works when given the FDs, I’m unable to translate and identify FDs for a given table.

I’ve been tasked to create a database of a company which tracks all expenses of sales/packages etc. Naturally that means storing Customer information for the company to identify all consumers.

CREATE TABLE Customers (
    id        integer primary key,
    address   text not null,
    name      text not null,
    email     text unique not null,
    phone     text unique not null,
    unique(name, address)
);
    

I’ve chosen to represent the info for the customer table as such, given that each phone number and email is uniquely tied to the customer. The unique constraint allows for multiple people from the same household address to be present in the table.

I want to see if I can normalize this table further, however I am unable to identify the attributes to determine the FDs needed.

views – field widget form element not updating #attributes via #ajax callback

I am trying to do a simple update to a form element in my field widget,

I have a start and a end dates in the field widget and I need the start date to be the min date of the end date,

so I call an ajax call back function to edit the $form array and return the element updated but it’s not working or updating the widget elements

can someone help me

use DrupalCoreFieldFieldItemListInterface;
use DrupalCoreFieldWidgetBase;
use DrupalCoreFormFormStateInterface;
use DrupalCoreDatetimeDrupalDateTime;
use DrupalComponentUtilityNestedArray;

/**
 * Plugin implementation of the 'work_slot_widget' widget.
 *
 * @FieldWidget(
 *   id = "work_slot_widget",
 *   module = "gag_work_slot",
 *   label = @Translation("Work slot widget"),
 *   field_types = {
 *     "work_slot_field"
 *   }
 * )
 */
class WorkSlotWidget extends WidgetBase
{

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings()
  {
    return (
      'increment' => '15',
      'date_order' => 'DMY',
      'time_order' => '24',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state)
  {
    $element = parent::settingsForm($form, $form_state);

    $element('date_order') = (
      '#type' => 'select',
      '#title' => t('Date part order'),
      '#default_value' => $this->getSetting('date_order'),
      '#options' => ('MDY' => t('Month/Day/Year'), 'DMY' => t('Day/Month/Year'), 'YMD' => t('Year/Month/Day')),
    );

    $element('time_order') = (
      '#type' => 'select',
      '#title' => t('Time type'),
      '#default_value' => $this->getSetting('time_order'),
      '#options' => ('24' => t('24 hour time'), '12' => t('12 hour time')),
    );

    $element('increment') = (
      '#type' => 'select',
      '#title' => t('Time increments'),
      '#default_value' => $this->getSetting('increment'),
      '#options' => (
        1 => t('1 minute'),
        5 => t('5 minute'),
        10 => t('10 minute'),
        15 => t('15 minute'),
        30 => t('30 minute'),
      ),
    );

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary()
  {
    $summary = ();
    $summary() = t('Date part order: @order', ('@order' => $this->getSetting('date_order')));
    $summary() = t('Time order: @time_order', ('@time_order' => $this->getSetting('time_order')));
    $summary() = t('Time increments: @increment', ('@increment' => $this->getSetting('increment')));
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
  {
    $field_name = $this->fieldDefinition->getName();
    $field_values = $form_state->getValue($field_name);
    $element('#theme_wrappers')() = 'fieldset';
    $element('work_slot_type') = (
      '#type' => 'select',
      '#title' => t('Work slot type'),
      '#description' => t('Select whether the work slot is single day or on going job'),
      '#default_value' =>  isset($field_values($delta)('work_slot_type')) ? $field_values($delta)('work_slot_type') : '',
      '#options' => (
        '' => t('Please select type of work slot'),
        'Single day' => t('Single day'),
        'On going' => t('On going job')
      ),
    );


    $date_order = $this->getSetting('date_order');
    $time_order = $this->getSetting('time_order');
    $increment = $this->getSetting('increment');
    // Set up the date part order array.
    switch ($date_order) {
      case 'YMD':
        $date_format = ('year', 'month', 'day');
        break;

      case 'MDY':
        $date_format = ('month', 'day', 'year');
        break;

      case 'DMY':
        $date_format = ('day', 'month', 'year');
        break;
    }

    switch ($time_order) {
      case '24':
        $time_format = ('hour', 'minute');
        break;

      case '12':
        $time_format =  ('hour', 'minute', 'ampm');
        break;

      case 'none':
        break;
    }
    $min_date = new DrupalDateTime('now');
    $min_date_str = $min_date->format('Y-m-d');
    $max_date = new DrupalDateTime('now');
    $max_date->modify('+1 year');
    $max_date_str =  $max_date->format('Y-m-d');
    $element('start_date') = (
      '#type' => 'date',
      '#title' => t('Start date'),
      '#date_date_format' => $date_format,
      '#date_date_element' => 'date',
      '#date_date_callbacks' => (),
      '#ajax' => (
        'callback' => ($this, 'startDateCallback'),
        'disable-refocus' => FALSE,
        'event' => 'change',
        'wrapper' => 'edit-start-dates',
        'progress' => (
          'type' => 'throbber',
          'message' => $this->t('updating...'),
        ),
      ),
      '#attributes' =>  ('min' => $min_date_str, 'max' => $max_date_str),
      '#states' => (
        'visible' =>
        (':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('!value' => ''),)
      ),
    );



    $end_min_date_str =  (isset($field_values($delta)('start_date'))) ?  $field_values($delta)('start_date') : $min_date_str;
    $element('end_date') = (
      '#type' => 'date',
      '#title' => t('End date'),
      '#date_date_format' => $date_format,
      '#date_date_element' => 'date',
      '#date_date_callbacks' => (),
      '#attributes' =>  ('min' => $end_min_date_str, 'max' => $max_date_str),
      '#states' => (
        'visible' =>
        (
          ':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('value' => 'On going'),
          'and',
          ':input(name="field_work_slot(' . $delta . ')(start_date)")' => ('!value' => '')
        )
      )
    );

    $element('times_container') = (
      '#type' => 'container',
      '#attributes' => (
        'id' => ('times_container'),
      ),
      '#states' => (
        'visible' =>
        (':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('!value' => ''),)
      ),
    );

    $element('times_container')('start_time') = (
      '#type' => 'datetime',
      '#title' => t('Start time'),
      '#date_date_element' => 'none',
      '#date_time_format' => $time_format,
      '#date_time_element' => 'time',
      '#date_time_callbacks' => (),
      '#states' => (
        'visible' =>
        (':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('!value' => ''),)
      ),
    );

    $element('times_container')('end_time') = (
      '#type' => 'datetime',
      '#title' => t('End time'),
      '#date_date_element' => 'none',
      '#date_time_format' => $time_format,
      '#date_time_element' => 'time',
      '#date_time_callbacks' => (),
      '#states' => (
        'visible' =>
        (':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('!value' => ''),)
      ),
    );

    $element('working_days') = (
      '#type' => 'select',
      '#title' => t('Working Days'),
      '#multiple' => TRUE,
      '#default_value' => 'All',
      '#states' => (
        'visible' =>
        (':input(name="field_work_slot(' . $delta . ')(work_slot_type)")' => ('value' => 'On going'),)
      ),
      '#options' => (
        'All' => t('All'),
        'Monday' => t('Monday'),
        'Tuesday' => t('Tuesday'),
        'Wednesday' => t('Wednesday'),
        'Thursday' => t('Thursday'),
        'Friday' => t('Friday'),
        'Saturday' => t('Saturday'),
        'Sunday' => t('Sunday'),
      ),
    );


    return $element;
  }
  /**
   * start date callback to set attributes for end date
   *
   * @param array $form
   * @param FormStateInterface $form_state
   * @return void
   */
  public function startDateCallback(array $form, FormStateInterface $form_state)
  {
    $triggered = $form_state->getTriggeringElement();
    $element = NestedArray::getValue($form, array_slice($triggered('#array_parents'), 0, -1));


    $element('start_date')('#attributes')('max') = $element('start_date')('#value');
    $element('end_date')('#attributes')('min') = $element('start_date')('#value');
    $element('end_date')('#value') = $element('start_date')('#value');
    return $element;
  }

Tags, categories or attributes for thematic item?

for a new website I need to use categories as geographic categories and I need to have something to indicate the pre-established thematic, just think about a news site with geographics categories full of posts with "economy" "chronicle" topic etc.

  • Categories: if I’ll use them I’ll have to find a way to separate the geographic cat from the thematic one in order to echo the second as topic in post listing.

  • Tag: the editor will no longer be able to use tags for other things, maybe seo etc

  • Attributes: it seems the best way, but how I can give to editor a default list instead of use them as text field in each post?

Any idea or suggestion?

magento2 – Where do scalar extension attributes save to?

Been reading the doc from Magento and i have been using extension attributes for more complex data structures but i’m basically wanting to add a simple scalar attribute

  <extension_attributes for="MagentoSalesApiDataShipmentTrackInterface">
    <attribute code="track_url" type="string"/>
  </extension_attributes>

And i thought for scalar attributes, i pretty much don’t need to do anything else such as adding plugins, just need to set the value correctly and use repository to save

        $shipment = $this->shipmentRepository->get($shipmentId);

        $track = $this->trackFactory->create()
            ->setTrackNumber('123')
            ->setCarrierCode('abc')
            ->setTitle('super delivery');


        $extensionAttributes = $track->getExtensionAttributes()->setTrackUrl(
            'http://www.trackme.com/abcdef'
        );
        $track->setExtensionAttributes($extensionAttributes);
      

        $shipment->addTrack($track);
        $this->shipmentRepository->save($shipment);

Codes are generated correctly, no errors, but when i try to retrieve it, it doesn’t actually return anything

$track->getExtensionAttributes()->getTrackUrl()

Am i misunderstanding extension attributes then? Does it mean i will always need to add something new to the database, even for scalar types?

magento2 – Magento 2 Adding extension attributes to MagentoSalesApiDataShipmentTrackInterface

I’m trying to add a custom track url to the trackings, using extension attributes, i added these in extension_attributes.xml

  <extension_attributes for="MagentoSalesApiDataShipmentTrackInterface">
    <attribute code="track_url" type="string"/>
  </extension_attributes>
    <extension_attributes for="MagentoSalesApiDataShipmentTrackCreationInterface">
        <attribute code="track_url" type="string"/>
    </extension_attributes>

Cleared the generated codes and caches, interfaces are populating correctly, I used MagentoSalesApiShipOrderInterface::execute and the $tracks argument has data looking like this:

[
  {
    "track_number": "1Z37X3X41217934386",
    "title": "ups",
    "carrier_code": "ups",
    "extension_attributes": {
      "track_url": "blah"
    }
  }
]

So everything looks fine and the extension attributes data are passed fine down to MagentoFrameworkModelAbstractExtensibleModel, however in MagentoFrameworkApiAbstractSimpleObject which is what MagentoSalesApiDataShipmentTrackExtension extends from, $data becomes an empty array, i still can’t figure out why this is happening, i’m in dev mode and shouldn’t need to run DI or something like that, any ideas?