Get orders collection between a date range in magento 2.

We just need to pass start date and end date to get collection between Specific time in Magento 2. We need to filter created_at field using addAttributeToFilter(). Create Block file.
By default created_at field in  sales_order table represent the time of order creation in Magento 2.

<?php
namespace Rbj\Order\Block;

class OrderRange extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        array $data = []
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
        parent::__construct($context, $data);
    }

    /* Order collection between start and end date */
    public function getOrderCollectionByDateRange(){
        $startDate = date("Y-m-d h:i:s",strtotime('2018-1-1')); // start date
        $endDate = strtotime("Y-m-d h:i:s", strtotime('2018-10-1')); // end date

        $orders = $this->orderCollectionFactory->create()
            ->addAttributeToFilter('created_at', array('from'=>$startDate, 'to'=>$endDate));
        return $orders;
    }
?>

Call Function from template file,

$orders = $block->getOrderCollectionByDateRange();

if($orders->getTotalCount() > 0) { 
    foreach($orders as $_order) {
        $orderId = $_order['increment_id'];
        echo "<pre>";print_r($_order);
    }
}

You can get Order collection by date range by the above tricks.

Setup upgrade Error, Invalid Document Element ‘resource’: The attribute ‘title’ is required but missing Magento 2

When we run php bin/magento setup:upgrade command through the command line, Sometimes error will throw like, Invalid Document Element ‘resource’: The attribute ‘title’ is required but missing.

This issue coming to Magento 2.2.* version when you run upgrade command.
This issue is related to acl.xml file. You missing the title attribute to <resource> tag. You must declare all the resource tag in acl.xml file with title attribute except all the resource tag which start with id=”Magento_Backend::”.

Check error code,

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Rbj_CustomForm::rbj">
                    <resource id="Rbj_CustomForm::customform" title="Customform Main" sortOrder="10">
                        <resource id="Rbj_CustomForm::manage_customform" title="Manage Customform" sortOrder="10" />
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

<resource id=”Rbj_CustomForm::rbj”> this tag with title attribute is missing, So you must set tag with title=”title name”.

Right code,

<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Rbj_CustomForm::rbj" title="Customform">
                    <resource id="Rbj_CustomForm::customform" title="Customform Slider" sortOrder="10">
                        <resource id="Rbj_CustomForm::manage_customform" title="Manage Customform" sortOrder="10" />
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

Run   Setup upgrade command and your error will be wiped out.

php magento setup:upgrade

 

How to Create customer and add new address programmatically in magento 2?

To create customer and customer addresses programmatically in Magento 2, You need to study the entire article and implement the code in your website.

Given the below code checks, the Customer exists or not using the email id. If the customer is new, Add a new customer and add the given address to the same customer otherwise display an already existing customer message.

<?php
$customerInfo =[
    'customer' =>[
        'firstname'    => 'Rakesh',
        'email'        => 'rakesh.jesadiya@aaaa.com', //customer email id
        'lastname'     => 'jesadiya',
        'password' => 'admin123',
        'prefix' => 'Mr',
        'suffix' => ''
    ],
    'address' =>[
        'firstname'    => 'Rakesh',
        'lastname'     => 'Jesadiya',
        'prefix' => 'Mr',
        'suffix' => '',
        'street' => 'Abcd street',
        'city' => 'Los Angeles',
        'country_id' => 'US',
        'region' => 'California',
        'region_id' => '12', // State region id
        'postcode' => '45454',
        'telephone' => '1234512345',
        'save_in_address_book' => 1
    ]
];

$block->createCustomer($customerInfo);

In the Block file, Pass customer-required data from the above $customerInfo array,

<?php

namespace Rbj\CreateCustomer\Block;

class CustomerAddress extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\Data\AddressInterfaceFactory $dataAddressFactory,
        \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->dataAddressFactory = $dataAddressFactory;
        $this->addressRepository = $addressRepository;
        parent::__construct($context, $data);
    }

    /** Create customer
     *  Pass customer data as array
     */
    public function createCustomer($data) {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($data['customer']['email']);// load customer by email to check if customer is availalbe or not
        if(!$customer->getId()){
            /* create customer */
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($data['customer']['firstname'])
                    ->setLastname($data['customer']['lastname'])
                    ->setPrefix($data['customer']['prefix'])
                    ->setMobile($data['customer']['mobile'])
                    ->setEmail($data['customer']['email'])
                    ->setPassword($data['customer']['password']);
            $customer->save();

            /* save address as customer */
            $address = $this->dataAddressFactory->create();
            $address->setFirstname($data['address']['firstname']);
            $address->setLastname($data['address']['lastname']);
            $address->setTelephone($data['address']['telephone']);

            $street[] = $data['address']['street'];//pass street as array
            $address->setStreet($street);

            $address->setCity($data['address']['city']);
            $address->setCountryId($data['address']['country_id']);
            $address->setPostcode($data['address']['postcode']);
            $address->setRegionId($data['address']['region_id']);
            $address->setIsDefaultShipping(1);
            $address->setIsDefaultBilling(1);
            $address->setCustomerId($customer->getId());
            try
            {
                $this->addressRepository->save($address);  
            }
            catch (\Exception $e) {
                return __('Error in shipping/billing address.');
            }
        } else {
            return __('Customer is already exist!');
        }
    }
    
}

Run the indexer command to see a customer in the admin panel,

php bin/magento indexer:reindex
php bin/magento cache:flush