magento2 – How to get orders based on custom attribute value of product?

I have a Custom attribute name ( product string ) on Product in which i have save a string i want to get those orders which will have that product string of same value.

I will get the product by :

$collection = $this->_orderCollectionFactory->create()
            ->addAttributeToSelect('*')
            ->setOrder('created_at','desc');
return $collection;

Get product list in custom admin grid form magento 2

I have a custom admin grid form, I want to select product like this when add or edit form
enter image description here

How can i do that?

Any help? Thank in advance.

looking for VPS that allows custom ISO/Windows Server ISO with my own license at the lowest price

Hi,

I am looking for unmanaged VPS that allows custom ISO/Windows Server ISO with my own license at the lowest price for my personal projec… | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1818050&goto=newpost

8 – D8 Custom Controller Custom Access, how to not return access denied page html

I’ve developed a custom controller that serves as a simple endpoint, POST method.

This controller has custom access control.

Custom access is done by looking for a header in the HTTP request, by making the controller object a service as well.

Everything works great. Except that when I return AccessResult::forbidden() .. I get the HTML of the access denied page .. and I don’t really want that .. I’d like to return just a short bit of JSON.

What can I do to return something that is JSON, and not the Access Denied page HTML, for this particular route, when the access() method returns AccessResult::forbidden() ?

I’ve read that appending ?_format=json to the url works, and in my case it does. Is there anyway to achieve the same result without adding this url parameter?

theming – User edit form on custom page is resetting roles when user belongs to the “Administrator role”

I’m trying to display the user edit form on a custom page with limited fields. Submitting my form works well, but if I have the Administrator role, roles are reset. I don’t understand why this is happening.

This is the routing file custom_user_profile.routing.yml.

my_module.default_controller_view:
  path: '/my_module'
  defaults:
    _controller: 'Drupalmy_moduleControllerDefaultController::view'
    _title: 'Account'
  requirements:
    _user_is_logged_in: 'TRUE'
  options:
    no_cache: 'TRUE'

In the controller DefaultController.php I have


namespace Drupalmy_moduleController;

use DrupalCoreControllerControllerBase;
use DrupaluserEntityUser;

class DefaultController extends ControllerBase
{

    public function view()
    {
        $user = User::load(Drupal::currentUser()->id());

        $html = '';
        $html .= '<p>Current email is ' . $user->mail->value . '</p>';

        $data('html') = (
            '#type' => 'markup',
            '#markup' => $html,
        );

        $user = User::load(Drupal::currentUser()->id());
        $formObject = Drupal::entityTypeManager()
            ->getFormObject('user', 'default')
            ->setEntity($user);

        $form = Drupal::formBuilder()->getForm($formObject);

        $data('form') = (
            'form' => $form,
        );

        return $data;

    }

}

In the my_module.module I have following code.

use DrupalCoreFormFormStateInterface;

function my_module_theme($existing, $type, $theme, $path)
{
    $templates = array(
        'my_module_about_form' => (
            'render element' => 'form',
        ),
    );

    return $templates;
}

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if ($form_id == 'user_form') {
        $form('#theme') = ('my_module_about_form');
    }
}

In the template file my-module-about-form.html.twig I have the following lines.

{{ form.timezone }}

{{ form.form_build_id }}
{{ form.form_token }}
{{ form.form_id }}
{{ form.actions.submit }}

magento2 – Magento 2 How to update custom order attribute after save invoice

i am using this –
di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_invoice_pay">
        <observer name="admin_after_invoice" instance="CompanynameModulenameObserverAdminAfterInvoice"/>
    </event>
</config>

AdminAfterInvoice.php

<?php
namespace CompanynameModulenameObserver;

use MagentoFrameworkEventObserverInterface;

class AdminAfterInvoice implements ObserverInterface
{
    private $orderRepository;

    public function __construct(
    MagentoSalesApiOrderRepositoryInterface $orderRepository      
    ) {

        $this->orderRepository = $orderRepository;
    }

    /**
     *
     * @param MagentoFrameworkEventObserver $observer
     * @return $this
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $invoice = $observer->getEvent()->getInvoice();
        $order1 = $invoice->getOrder();
        $writer = new ZendLogWriterStream(BP . '/var/log/xyz.log');
        $logger = new ZendLogLogger();
        $logger->addWriter($writer);
        $logger->info('Invoice Order status----------'.$order1->getStatus());
        $logger->info('Invoice Order id----------'.$order1->getId());

        $orderId = $order1->getId();
        try{
            $logger->info('invoice try----------');
            $objectManager = MagentoFrameworkAppObjectManager::getInstance(); // Instance of object manager
            $order = $objectManager->create('MagentoSalesModelOrder')->load($orderId);
            $order->setCustomAttribute1("status2");
            $order->setCustomAttribute2("1");
            $order->save();
        } catch (NoSuchEntityException $ex) {
            $logger->info('invoice catch----------'.json_encode($ex->getMessage()));
        }
    }
}

Does anyone know how to update the custom order attribute?

custom post types – How to trigger a function when submit a form

How can I make work these functions not just when the user profile is updated. Also when a frontend form is submited?

Here the functions:

function get_channel_by_author( $user_id ) : int {
// if we don't find anything then a value of 0 will create a new post rather than update an existing post.
$channel_id = 0;
$args = (
    'post_type'      => 'channel',
    'posts_per_page' => 1,
    'post_author'    => $user_id,
);
$query     = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $channel_id = get_the_ID();
        // we only want a single post ID
        break;
    }
    // cleanup after the query
    wp_reset_postdata();
} else {
    // perhaps the channel was created before post authors were set? Fall back to looking for the post by its slug/name
    return 0;
}
return $channel_id;
}

function get_channel_by_slug( string $slug ) : int {
    $channel_id = 0;
    $args = (
        'post_type'      => 'channel',
        'posts_per_page' => 1,
        'post_name'      => $slug,
    );
    //... etc etc see get_channel_by_author ...
    return $channel_id;
}

function handle_channel_post( $user_id = '' ) {
    // First, is this user an instructor?
    $user = get_user_by( 'ID', $user_id );
    if ( ! $user || ! in_array( 'instructor', $user->roles, true ) ) {
        return;
    }

    // get the channel name
    $channel_name = get_user_meta( $user_id, 'channel_name', true );
    if ( empty( $channel_name )) {
        error_log( "the user does not have a channel_name!" );
    }

    // Then lets find this users channel if it exists.
    // if we don't find anything then a value of 0 will create a new post rather than update an existing post.
    $channel_id = get_channel_by_author( $user_id );
    if ( $channel_id === 0 ) {
        // we didn't find a channel with that author, try the channel name.
        $channel_id = get_channel_by_slug( $channel_name );
    }


    // Finally, save/update the channel!
    $content .= get_user_meta( $user_id, 'description_channel', true );
    $args     = (
        'ID'           => $channel_id,
        'post_title'   => $channel_name,
        'post_name'    => $channel_name, // set the slug/permalink
        'post_content' => $content,
        'post_status'  => 'publish',
        'post_type'    => 'channel',
    );
    $post_id  = wp_insert_post( $args );

    // check if we were succesful.
    if ( is_wp_error( $post_id ) ) {
        // it didn't work!
        error_log( $post_id->get_error_message() );
    } else if ( empty( $post_id ) ) {
        // it didn't work!
        error_log( "post_id is empty/false" );
    }

 }

add_action( 'personal_options_update', 'handle_channel_post' );
add_action( 'edit_user_profile_update', 'handle_channel_post' );

And this is the form where it gets the meta fields to the user profile. This works fine.

What I’m trying to figure out is an add action that triggers these functions when submiting the form. So it creates or updates the channel custom post type after submiting.

<?php 
if ( is_user_logged_in() ) : 
    $current_user = wp_get_current_user();
    $c_user_id = $current_user->ID;
    $channel_name = get_user_meta( $c_user_id, 'channel_name', true);  ?>              
    <form method="post" id="adduser" action="<?php the_permalink(); ?>">
        <p class="form-email" style="display:none;">
             <label for="email"><?php _e('E-mail *', 'profile'); ?></label>
             <input class="text-input" name="email" type="text" id="email" value="<?php the_author_meta( 'user_email', $current_user->ID ); ?>" />
         </p><!-- .form-email -->
         <?php 
         //action hook for plugin and extra fields
         do_action('edit_user_profile',$current_user); 
         ?>
         <p class="form-submit">
              <input name="updateuser" type="submit" id="updateuser" class="submit button" value="<?php _e('Update', 'profile'); ?>" />
              <?php wp_nonce_field( 'update-user' ) ?>
              <input name="action" type="hidden" id="action" value="update-user" />
              <span>Go to your <a href="https://example.com/wp-admin/admin.php?page=ir_instructor_overview">dashboard</a></span>
          </p><!-- .form-submit -->
    </form><!-- #adduser -->
        <?php
else  : ?>
    <p class="warning">
        <?php _e('You must log in <a href="https://example.com/login">here</a> to edit your profile.', 'profile'); ?>
    </p><!-- .warning -->
<?php
endif; ?>

Appreciate your time

What is the correct way that when creating a custom post type assign values to custom fields created with pods framework?

I am trying to create a custom post type input using the wp_insert_post function, this custom post type called game was created using the pods framework and contains a series of custom fields which I try to give values using the meta_input key as follows

Example using _pods_ prefix

$entry = (
    "post_title" => "{$post->post_title} - {$game->number}",
    "post_content" => "... {$id}",
    "post_type" => "game",
    "post_status" => "publish",
    "meta_input" => (
        "_pods_game_number" => $game->number,
        "_pods_game_date" => $game->date,
        "_pods_fields" => $fields,
        "_pods_league" => $id,
    )
);
$game_id = wp_insert_post($entry, true);

Example with no prefix

$entry = (
    "post_title" => "{$post->post_title} - {$game->number}",
    "post_content" => "... {$id}",
    "post_type" => "game",
    "post_status" => "publish",
    "meta_input" => (
        "game_day_number" => $game->number,
        "game_day_date" => $game->date,
        "fields" => $fields,
        "league" => $id,
    )
);
$game_day_id = wp_insert_post($entry, true);

For some reason the meta fields are not saved except for the fields field … Investigating I read somewhere about using the _pods_ prefix in custom fields but although I can verify that the fields and their correct values are created in the postmeta table these are not listed in the form. If on the other hand I try to reference the custom fields without the prefix _pods_ they are not created, I confirm this by looking for them in the postmeta table.

What is the correct way that when creating a custom post type assign values to custom fields created with pods framework?

I appreciate your time