magento2 – Magento 2 how add extension attribute to order item

I need to save the extension attribute for Order item. I have tried using plugin with below code, but it is not working for me. I have placed a log inside the method but the method is not working.

<type name="MagentoSalesApiOrderItemRepositoryInterface">
    <plugin name="order_item_extension_attr" type="VendorCustomModulePluginModelTest"/>
</type>

public function afterGet(
        MagentoSalesApiOrderItemRepositoryInterface $orderItem, 
        MagentoSalesApiDataOrderItemExtensionInterface $extension = null
    ) {

}

How to save and get order item extension attribute?

magento2 – Get a Custom Customer Attribute to Appear on the Checkout Success Page

I’ve recently created a new module for my Magento ver. 2.3.5-p1 instance using the following blog:

Magento 2.1.3 Make Customer Attribute [Update]

The module has worked properly and created a new customer attribute with the i.d. “magento_username”.

I would now like to add this attribute to the checkout success page but I’m not sure how to do this, what I was thinking was something like the below:

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

?>
<?php /** @var $block MagentoCheckoutBlockOnepageSuccess */ ?>
<div class="checkout-success">

     <p>Thank you for your order <?= $customerMagentoUsername()= $item->getMagentoUsername(); ?> </p>

    <?php if ($block->getOrderId()) :?>
        <?php if ($block->getCanViewOrder()) :?>
            <p><?= $block->escapeHtml(__('Your order number is: %1.', sprintf('<a href="%s" class="order-number"><strong>%s</strong></a>', $block->escapeUrl($block->getViewOrderUrl()), $block->getOrderId())), ('a', 'strong')) ?></p>
        <?php  else :?>
            <p><?= $block->escapeHtml(__('Your order # is: <span>%1</span>.', $block->getOrderId()), ('span')) ?></p>
        <?php endif;?>
            <p><?= $block->escapeHtml(__('We'll email you an order confirmation with details and tracking info.')) ?></p>
    <?php endif;?>

    <?= $block->getAdditionalInfoHtml() ?>

    <div class="actions-toolbar">
        <div class="primary">
            <a class="action primary continue" href="<?= $block->escapeUrl($block->getContinueUrl()) ?>"><span><?= $block->escapeHtml(__('Continue Shopping')) ?></span></a>
        </div>
    </div>
</div>

magento2 – Magento 2 customer attribute not working in Magento 2.3.3

I have created a module for adding a customer attribute and show it in create account form on frontend and account edit in backend, the thing is that it worked in Magento 2.2 but not on Magento 2.3.3, I don’t know if it changes.

Here is my code.

InstallData.php

<?php
namespace KageRegisterFormSetup;

use MagentoCustomerApiCustomerMetadataInterface;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface 
{
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;
    /**
     * @var MagentoEavModelConfig
     */
    private $eavConfig;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        MagentoEavModelConfig $eavConfig
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }

    /**
     * Installs data for a module
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var MagentoEavSetupEavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(('setup' => $setup));

        $setup->startSetup();

        $attributeCode = 'register_zip_code';
        $eavSetup->addAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'register_zip_code', (
            'type' => 'text',
            'label' => 'Zip Code',
            'input' => 'text',
            'required' => true,
            'visible' => true,
            'source' => '',
            'backend' => '',
            'user_defined' => true,
            'is_user_defined' => false,
            'sort_order' => 1000,
            'is_used_in_grid' => false,
            'is_visible_in_grid' => false,
            'is_filterable_in_grid' => false,
            'is_searchable_in_grid' => false,
            'position' => 1000,
            'default' => 0,
            'system' => 0,
        ));

        $eavSetup->addAttributeToSet(
            CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
            CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
            null,
            $attributeCode);

        $registerZipCode= $this->eavConfig->getAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, $attributeCode);
        $registerZipCode->setData('used_in_forms', (
            'adminhtml_customer',
            'customer_account_create',
            'customer_account_edit'
        ));
        $registerZipCode->getResource()->save($registerZipCode);

        $setup->endSetup();
    }
}

view/frontend/layout/customer_account_create.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="form.additional.info">
                <block class="MagentoFrameworkViewElementTemplate" name="register_zip_code" template="Kage_RegisterForm::register.phtml"/>
    </referenceContainer>
</body>
</page>

view/templates/register.phtml

<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
    <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Additional Information') ?></span></legend>
    <p>
    <div class="field required regulation">
        <label for="regulation" class="label"><span><?php /* @escapeNotVerified */
                echo __('Zip Code') ?></span></label>
        <div class="control">
            <input type="text" name="register_zip_code" id="register_zip_code" title="<?php /* @escapeNotVerified */ echo __('Zip Code') ?>" class="input-text" data-validate="{required:true}">
        </div>
    </div>
    </p>
</fieldset>

magento2 – Magento 2 customer attribute not saved in database

So I have created an attribute for customer entity, used it in frontend create account form, but it’s not showing anything in customer_entity_varchar table, it’s empty. However, in eav_attribute table I can see my attribute created.

Here is my code how I create the attribute.

InstallData.php

<?php
namespace KageRegisterFormSetup;

use MagentoCustomerApiCustomerMetadataInterface;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;

class InstallData implements InstallDataInterface 
{
    /**
     * @var EavSetupFactory
     */
    private $eavSetupFactory;
    /**
     * @var MagentoEavModelConfig
     */
    private $eavConfig;

    public function __construct(
        EavSetupFactory $eavSetupFactory,
        MagentoEavModelConfig $eavConfig
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }

    /**
     * Installs data for a module
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var MagentoEavSetupEavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(('setup' => $setup));

        $setup->startSetup();

        $attributeCode = 'register_zip_code';
        $eavSetup->addAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'register_zip_code', (
            'type' => 'text',
            'label' => 'Zip Code',
            'input' => 'text',
            'required' => true,
            'visible' => true,
            'source' => '',
            'backend' => '',
            'user_defined' => true,
            'is_user_defined' => false,
            'sort_order' => 1000,
            'is_used_in_grid' => false,
            'is_visible_in_grid' => false,
            'is_filterable_in_grid' => false,
            'is_searchable_in_grid' => false,
            'position' => 1000,
            'default' => 0,
            'system' => 0,
        ));

        $eavSetup->addAttributeToSet(
            CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
            CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
            null,
            $attributeCode);

        $registerZipCode= $this->eavConfig->getAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, $attributeCode);
        $registerZipCode->setData('used_in_forms', (
            'adminhtml_customer',
            'customer_account_create',
            'customer_account_edit'
        ));
        $registerZipCode->getResource()->save($registerZipCode);

        $setup->endSetup();
    }
}

Template register.phtml

<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
    <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Additional Information') ?></span></legend>
    <p>
    <div class="field required regulation">
        <label for="regulation" class="label"><span><?php /* @escapeNotVerified */
                echo __('Zip Code') ?></span></label>
        <div class="control">
            <input type="text" name="register_zip_code" id="register_zip_code" title="<?php /* @escapeNotVerified */ echo __('Zip Code') ?>" class="input-text" data-validate="{required:true}">
        </div>
    </div>
    </p>
</fieldset>

After I submit the form, It’s not saved.

Greetings!

client server – HTTP 400 or 404 when a composite attribute entity not found

I have a POST endpoint for creating a new entity, let’s say a Contract. It takes two attributes: User ID and Company ID. The result Contract is created as a composite of those.

The request:

POST /contracts
{ "userId": 1, "companyId": 2 }

If the User or the Company is not found under the provided ID. What is the best answer to the client? 400 or 404?

One can argue for both:

400 – The endpoint exists but the resource cannot be created due to an invalid request parameter (ID).

404 – The needed entity (User or Company) is not found, so 404 – not found.

A similar question was already asked here (Question 2.), but was not fully addressed, or at least not clearly.

magento2 – Status attribute missing values

After building a new Magento (2.3.5-p1) webshop and imported the products and categories from the old Magento 1 webshop, I have now the problem that a duplicated product is not showing in the frontend. The product is enabled in the backend.

When I wanted to add the product to an order in the backend, I got the notice the product was disabled.

I checked the product status attribute in th e backend and noticed that it had no values. Is it possible to restore the values with SQL? In the backend it is not possible.

python – How can I handle this error: “TypeError: ‘int’ object has no attribute ‘__getitem__’ “

I am trying to simulate a system consisting of 4 masses which are attached with a springs. Leftmost and rightmost masses are fixed. Other two masses are free to move. When I run the code, I face this error:

TypeError: 'int' object has no attribute '__getitem__' 

All the code is below:

import numpy as np

L = 1
k = 1
m = 1

def GetAcc(pos):
    N = 4
    acc = np.zeros(N)
    
    for i in range(1, N-1):
        acc = -(k/m) * (2*pos(i)-pos(i-1)-pos(i+1))
    
    return acc

def UpdatePos(x, v, a, dt):
    return x + v*dt + 0.5*a*dt**2

def UpdateVel(v, a, dt):
    return v + a*dt

def Simulate(dt, x, v_x):
    num_particles = len(x)

    a_x = GetAcc(x)

    for i in range(num_particles):
        v_x(i) = UpdateVel(v_x(i), a_x(i), dt)
    
    for i in range(num_particles):
        x(i) = UpdatePos(x(i), v_x(i), a_x(i), dt)

    return x

num_particles = 4

x = (0, 1, 2, 3)
y = (0, 0, 0, 0)
z = (0, 0, 0, 0)

v_x = (0) * num_particles

number_of_steps = 100

for i in range(number_of_steps):
    x = Simulate(0.1, x, v_x)

    print(num_particles)
    print "C"

    for j in range(4):
        print "C", x(j), y(j), z(j)

functions – Link product attribute value to a URL – woocommerce

I would like to add a local product attribute value that will have a link which points to a particular ‘href’ value. I followed this blog and tried to add via the markup option mentioned at the end of the blog, the value turns into an anchor tag link but the href value is not taken properly.
https://nicolamustone.blog/2016/03/11/make-product-attributes-linkable/

I added this snippet from the blog in my functions.php

/**
 * Register term fields
 */
add_action( 'init', 'register_attributes_url_meta' );
function register_attributes_url_meta() {
        $attributes = wc_get_attribute_taxonomies();

        foreach ( $attributes as $tax ) {
            $name = wc_attribute_taxonomy_name( $tax->attribute_name );

            add_action( $name . '_add_form_fields', 'add_attribute_url_meta_field' );
            add_action( $name . '_edit_form_fields', 'edit_attribute_url_meta_field', 10 );
            add_action( 'edit_' . $name, 'save_attribute_url' );
            add_action( 'create_' . $name, 'save_attribute_url' );
        }
}

/**
 * Add term fields form
 */
function add_attribute_url_meta_field() {

    wp_nonce_field( basename( __FILE__ ), 'attrbute_url_meta_nonce' );
    ?>

    <div class="form-field">
        <label for="attribute_url"><?php _e( 'URL', 'domain' ); ?></label>
        <input type="url" name="attribute_url" id="attribute_url" value="" />
    </div>
    <?php
}

/**
 * Edit term fields form
 */
function edit_attribute_url_meta_field( $term ) {

    $url = get_term_meta( $term->term_id, 'attribute_url', true );
    wp_nonce_field( basename( __FILE__ ), 'attrbute_url_meta_nonce' );
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="attribute_url"><?php _e( 'URL', 'domain' ); ?></label></th>
        <td>
            <input type="url" name="attribute_url" id="attribute_url" value="<?php echo esc_url( $url ); ?>" />
        </td>
    </tr>
    <?php
}

/**
 * Save term fields
 */
function save_attribute_url( $term_id ) {
    if ( ! isset( $_POST('attribute_url') ) || ! wp_verify_nonce( $_POST('attrbute_url_meta_nonce'), basename( __FILE__ ) ) ) {
        return;
    }

    $old_url = get_term_meta( $term_id, 'attribute_url', true );
    $new_url = esc_url( $_POST('attribute_url') );


    if ( ! empty( $old_url ) && $new_url === '' ) {
        delete_term_meta( $term_id, 'attribute_url' );
    } else if ( $old_url !== $new_url ) {
        update_term_meta( $term_id, 'attribute_url', $new_url, $old_url );
    }
}

/**
 * Show term URL
 */
add_filter( 'woocommerce_attribute', 'make_product_atts_linkable', 10, 3 );
function make_product_atts_linkable( $text, $attribute, $values ) {
    $new_values = array();
    foreach ( $values as $value ) {

        if ( $attribute('is_taxonomy') ) {
            $term = get_term_by( 'name', $value, $attribute('name') );
            $url = get_term_meta( $term->term_id, 'attribute_url', true );

            if ( ! empty( $url ) ) {
                $val = '<a href="' . esc_url( $url ) . '" title="' . esc_attr( $value ) . '">' . $value . '</a>';
                array_push( $new_values, $val );
            } else {
                array_push( $new_values, $value );
            }
        } else {
            $matched = preg_match_all( "/(((^))+))(((^))+))/", $value, $matches );

            if ( $matched && count( $matches ) == 3 ) {
                $val = '<a href="' . esc_url( $matches(2)(0) ) . '" title="' . esc_attr( $matches(1)(0) ) . '">' . sanitize_text_field( $matches(1)(0) ) . '</a>';
                array_push( $new_values, $val );
            } else {
                array_push( $new_values, $value );
            }
        }
    }

    $text = implode( ', ', $new_values );

    return $text;
}

I added the cutom attribute value as : (Displayed text)(https://expected-display-url.com)

What I expected it to output:

<a href="https://expected-display-url.com">Displayed text</a> 

But what it converted instead:

<a title="Displayed text">Displayed text</a> 

Even when I tried to add a specific title value like: (Displayed text)(https://expected-display-url.com "title")

It always rendered as: <a title="Displayed text">Displayed text</a>

magento2 – Visual editor for custom order attribute

It’s possible to add a visual input on user infos form, is it possible to do this to my orders ?

I already add the column in filters and I did this to add the field :

$salesSetup->addAttribute(Order::ENTITY, 'order_custom_attr', (
    'type' => MagentoFrameworkDBDdlTable::TYPE_TEXT,
    'length'=> 255,
    'visible' => false,
    'nullable' => true,
));