Quantcast
Channel: Webkul Blog
Viewing all 5480 articles
Browse latest View live

How To Add Custom Field At Billing Address Form In Magento 2

$
0
0

How To Add Custom Field At Billing Address Form In Magento 2 : In this post, i’ll explain how we can add custom fields in billing address form at checkout. so just follow these steps.

1 => As we know that billing and shipping forms are generated dynamically. so we need to create a plugin for the \Magento\Checkout\Block\Checkout\LayoutProcessor::process method.
so for create the plugin first we should make an entry in di.xml on this path.
app/code/CompanyName/Module/etc/frontend/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="add_custom_field_checkout_form" type="CompanyName\Module\Model\Plugin\Checkout\LayoutProcessor" sortOrder="100"/>
    </type>
</config>

2 => Create plugin class on this Directory.
app/code/CompanyName\Module\Model\Plugin\Checkout

namespace Webkul\CompanyName\Module\Plugin\Checkout;
class LayoutProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {
        $configuration = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'];
        foreach ($configuration as $paymentGroup => $groupConfig) {
            if (isset($groupConfig['component']) AND $groupConfig['component'] === 'Magento_Checkout/js/view/billing-address') {

                $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                ['payment']['children']['payments-list']['children'][$paymentGroup]['children']['form-fields']['children']['company_tax_id'] = [
                    'component' => 'Magento_Ui/js/form/element/abstract',
                    'config' => [
                        'customScope' => 'billingAddress.custom_attributes',
                        'template' => 'ui/form/field',
                        'elementTmpl' => 'ui/form/element/input',
                        'options' => [],
                        'id' => 'custom-field'
                    ],
                    'dataScope' => 'billingAddress.custom_attributes.custom_field',
                    'label' => 'Custom Field',
                    'provider' => 'checkoutProvider',
                    'visible' => true,
                    'validation' => [],
                    'sortOrder' => 250,
                    'id' => 'custom-field'
                ];
            }
        }


        return $jsLayout;
    }
}


Now custom field will be visible at billing form.

Hope so it will you help you.


Closures in PHP

$
0
0

Today we will learn a very interesting topic known as closure. PHP started support of closure with version 5.3.0. Before understanding closure term first we have to understand some terms. which are-
Lazy Loading: – Lazy loading terms that the loading of an object is delayed until it is really required.
Anonymous function: – An anonymous function is a function without name. It is assigned to a variable or provided as a parameter to another function.  Let us see an example for anonymous function-

<?php
 $webkul = function() {
	return "Hi you are in  anonymous function.";
 };
 //anonymous function have semicolon at last

echo $webkul();

?>
//output: Hi you are in  anonymous function.

In this example we have created a function which have a return string and assign to a variable $webkul , this variable is then called as a function . Note that anonymous function always  ends with a semicolon.

Now we can understand closure very well. A closure is an object representation of an anonymous function. We can see that the anonymous function in the above code actually returns an object of closure which is assigned to and called using the variable $webkul. You can say closure is an object oriented way to use anonymous functions. Closure can access data external to it. For example. It can access data of the class, inside class any function in which it is written or if it is not written in any class or function it can access the data directly specified. To use external data, it has to be specified in the use clause of the closure. Take a look at this example.

<?php
$user="Webkul demo";
$showMe=function() use($user){
echo "Welcome ".$user;
};
//Call $showMe variable as function to see o/p
$showMe();
?>
//output: Welcome Webkul demo

Here, we have a value “Webkul demo” in variable $user . It is accessed inside the anonymous function using use keyword. The closure object is stored in $showMe variable and then the function is called using this variable. Now If you want to change the value of external variable accessed inside the closure, you can do it by passing the value by reference so that the change occurs at the actual location of the value And actual value will be remain same. for example –

<?php
$department="Opencart";
$output=function() use(&$department){
$department="Magento";
echo "Welcome to ".$department;
};
echo "Before change  in closure function:<br>";
echo "Welcome to ".$department;
// OUTPUT -> Before change  in closure function: Welcome to Opencart
echo "After change  in closure function:<br>";
echo "Welcome to ";
$output();
//  OUTPUT ->  After change  in closure function:  Welcome to Magento
?>

Here we have  variable $department which have actual value “Opencart” .Now inside the closure we have used this variable by  call by reference and change value to “magento”.  Closures can also access all the private data of a class. Lets see an example for this-

<?php
class webkul
{
	private $id;
	private $emp;
	
	public function __construct($id,$emp)
	{
		$this->id=$id;
		$this->emp=$emp;
	}
	
	public function info(){
			return function(){
			return "ID = {$this->id} <br>Employee = {$this->emp}.";
		};
	}
	
}
$webkulEmp1 = new webkul(101,'opencartEmployee');
$webkulEmp1->info();
//output: 
// ID = 101 
// Employee = opencartEmployee.

Here we are accessing the private members $id and $emp in the closure, which are defined as private. But we use them with help of inside function closure. If  a closure defined inside a class and if you don’t want to allow it to use the data in the class, you can use static keyword. When we use static keyword with a closure , then  closure is not allowed to use the data in the class.

<?php
class staticClosure {
	private $id;
	
	public function __construct($id) {
		$this->id=$id;
	}
	public function company($name) {
		return static funciton() use($name) {
			echo "This is a ".$name." staticClosure.";
		}; 
	}
}

$staticClosure=new staticClosure();
$staticClosure->company("Webkul Soft");
?>

This will help save memory needed to store the object data when used in the closure. This is more useful when you use more than one closure in a class with static keyword. Thus we have learned closure in this blog. It is very useful to use closures in place of  functions when we require to perform a small task and in this task will  be used only once in the script.

CS-Cart Block.io Bitcoin Wallet

$
0
0

CS-Cart Block.io Bitcoin Wallet:
Now allow your customers to pay via Bitcoins on your store and make their checkout experience quite fast and secure. CS-Cart Block.io Bitcoin Wallet add-on integrates block.io with CS-Cart. This allows store admin to enable bitcoin payment at his store. It also lets you have a greater control over the checkout experience so that you can test and implement the most effective experience for your store. It is one of the most reliable and secure payment solutions and monitors the transactions in real time.

Features

  • Well integrated with CS-Cart Multi-Vendor.
  • Integrates with block.io, the most versatile and secure wallet for bitcoins.
  • Admin can enable bitcoin payment at his store.
  • Functionality to generate bitcoin address for the user.
  • The user can request for Bitcoin wallet/address from the profile page while registering at CS-Cart store.
  • Functionality to generate a bitcoin address for the user who does not have one during payment.
  • Easy to configure and manage at admin end.

How To Upload and Install

After downloading CS-Cart Block.io Bitcoin Wallet, you will get a zip file and install.txt . Read the install.txt carefully and configure it accordingly.

Go to “Manage add-ons”, click on “+” to upload and install the zip file as shown below.
Upload
Click on “Local” to browse the zip file and then click on “Upload & Install” as shown below in snapshot.
CS-Cart Block.io Bitcoin Wallet

Configuration

After installing CS-Cart Block.io Bitcoin Wallet, Click on Settings as shown below :

settings

Enter the Block API key and Block API Pin  &  Save the settings.

settings done

Back End View

Go to “Administration” tab and click on “Payment methods”.

Backend

Click on “+” to create a new payment method.

Add Payment Method

Set the parameters as shown below in the snapshot.

  • Set the name of the payment method.
  • For checkout choose the processor as “Block.io Payment”.
  • Select template as “cc_outside.tpl” from the dropdown.
  • Configure the tabs accordingly as shown below in the snapshot.

configure

Click on “Configure” and set the parameters as shown below in the snapshot.

  • Enter the Bitcoin Wallet Address of Admin where the order amount is received.
  • Enter the Exchange rate.
  • Set the order status which needs to be updated on successful bitcoin payment.
  • Save the settings.

configure2

Front End View

Once the payment method is configured,  option for payment via Bitcoin is available for customers at the front end. For payment, customer needs to select the option as shown below in the snapshot and enter the necessary details for payment.

frontend

If the customer does not have Bitcoin wallet Address, it gets created automatically. Also, the user can request for a bitcoin wallet address while registering on your store as shown below.

user register

The user can check bitcoin address under his profile details at the front end as shown below.

blockio

A separate tab, Block.io gets created and Bitcoin address is mentioned under that tab.

wallet address

Back End View

Store admin can view the Bitcoin address of the customer in Customer Profile page at backend.

Go to Customers -> Customers and open the profile page of the customer. Click on Add-ons to view the bitcoin address of that customer.

customer backend

Support

This is all about CS-Cart Block.io Bitcoin Wallet. Still have any issue, feel free to contact us at http://webkul.uvdesk.com and let us know your views to make the module better.

Joomla Social Messaging

$
0
0

Joomla Social Messaging:

Joomla Social Messaging is a wonderful plugin for Joomla users, it provides a functionality by which Joomla site admin can provide a social messaging feature for Twitter and Facebook users on his Joomla website. Any user with their login to these social platforms can message directly to Joomla site admin’s social account( Twitter and Facebook) using this extension.

FEATURES-

  • Fully configurable – Admin can configure fields such as header background color,font color, text to be displayed, height,width,tabs color etc.
  • Messiging option is available for Facebook and Twitter.
  • Easily configurable – Just fill the credentials and it is ready to use, for your Joomla site.
  • Admin can set position left/right, Where to place Social Message container.
  • User can send message easily. Only needs to login into their Twitter/Facebook account.
  • Admin can enable/disable Facebook/Twitter Messaging as per interest.

FLOW OF INSTALLATION AND CONFIGURATION

Step1.
Browse the ‘Joomla Social Messaging’ zip file and then upload and install.

Browse_upload and install

Step2.
Now, click on ‘Extensions’ and move to ‘Plugins’ in the drop-down and click on it.

Click on extensions

Step3.
Search the required plugin – Joomla Social Messaging and click on it, and make the plugin enable.

Plugin_setting

Step4.
Then next one “Basic Setting”

Basic_setting

Step5.
Next one “Facebook Setting”

Facebook_setting

Step6.
Next one “Twitter Setting”

Twitter_setting
Twitter_setting_1

Step7.
Now, in this step you can see who you to create “Twitter App”, first you need to login to https://apps.twitter.com/

Twitter Application Management
Create an application - Twitter Application Management

FRONT-END VIEW

Ste8.
This is the front-end view, here you can see that at how the Joomla social messaging looks at Joomla website front-end.

Front-end_view
Site_front-end_1 jpg

Now click on any social media platform let say “Twitter” then click on “Twitter tab and open it with your Twitter account credentials then enter your message.
Joomla Social Messaging_frontend

This is Joomla site admin Twitter message box, where admin can see the message send by any walking user from Joomla social messaging.
Twitter_inbox

WEBKUL SUPPORT

That’s all for the Joomla Social Messaging still, have any issue feel free to add a ticket and let us know your views to make the Plugin better http://webkul.uvdesk.com

How to create dynamic component on a button click in Lightning

$
0
0

In this blog, we will learn how to create a dynamic component on a button click in Lightning. Let’s get started!

Create Dynamic Component on button click

To create a dynamic component, first of all, you need to create a Lightning Event, in which you define a parameter of the component type.

<!--RemoveComponent.evt-->
<aura:event type="COMPONENT" description="Event template" >
<!-- 
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
     -->
    <aura:attribute name="comp" type="Aura.Component"/>
</aura:event>

Now, on a button click we have to create a component, let us take an example of the model for this. We will first create the Modal component which will appear on the button click, and we will also register the event for removing it.

Component-

<!--Modal.cmp-->
<aura:component >
    <!-- 
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
     -->
    <ltng:require styles="{!$Resource.SLDS +'/assets/styles/salesforce-lightning-design-system-ltng.css'}"/>
    
    <!--Initialize the component-->
    <aura:handler name="init" value="{!this}" action="{!c.applycss}"/>
    
    <!--Register Event-->
    <aura:registerEvent name="RemoveComponent" type="c:RemoveComponent"/>
	
    <div class="wk_static">
        
        <!--Create a modalbox using Salesforce Lightning Desing System-->
        <div role="dialog" tabindex="-1" aura:id="Modalbox" aria-labelledby="header43" class="slds-modal ">
            <div class="slds-modal__container">
                <div class="slds-modal__header">
                    <button class="slds-button slds-button--icon-inverse slds-modal__close" onclick="{!c.removeComponent}">
                        <span>
                            <c:SVG class="slds-button__icon slds-button__icon--large" xlinkHref="/resource/SLDS/assets/icons/action-sprite/svg/symbols.svg#close" />
                            <span class="slds-assistive-text">Close</span>
                        </span>                 
                    </button>
                    <h2 id="header43" class="slds-text-heading--medium">Modal Header</h2>
                </div>
                <div class="slds-modal__content slds-p-around--medium">
                    <div>
                        <p>Sit nulla est ex deserunt exercitation anim occaecat. Nostrud ullamco deserunt aute id consequat veniam incididunt duis in sint irure nisi. Mollit officia cillum Lorem ullamco minim nostrud elit officia tempor esse quis. Cillum sunt ad dolore
                        quis aute consequat ipsum magna exercitation reprehenderit magna. Tempor cupidatat consequat elit dolor adipisicing.</p>
                        <p>Dolor eiusmod sunt ex incididunt cillum quis nostrud velit duis sit officia. Lorem aliqua enim laboris do dolor eiusmod officia. Mollit incididunt nisi consectetur esse laborum eiusmod pariatur proident. Eiusmod et adipisicing culpa deserunt
                        nostrud ad veniam nulla aute est. Labore esse esse cupidatat amet velit id elit consequat minim ullamco mollit enim excepteur ea.</p>
                    </div>
                </div>
                <div class="slds-modal__footer">
                    <button class="slds-button slds-button--neutral" onclick="{!c.removeComponent}">Close</button>
                </div>
            </div>
        </div>
        <div class="slds-backdrop " aura:id="MB-Back"></div>
        
    </div>
</aura:component>

Controller-

//ModalController.js
({   
       /**
	 * Webkul Software.
	 *
	 * @category  Webkul
	 * @author    Webkul
	 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
	 * @license   https://store.webkul.com/license.html
	**/ 
    applycss:function(cmp,event){
	//initialize        
        var cmpTarget = cmp.find('Modalbox');
       	var cmpBack = cmp.find('MB-Back');
        $A.util.addClass(cmpTarget, 'slds-fade-in-open');
        $A.util.addClass(cmpBack, 'slds-backdrop--open'); 
    },
    removeComponent:function(component, event, helper){
        //get event and set the parameter of Aura:component type, as defined in the event above.
        var compEvent = component.getEvent("RemoveComponent");
        compEvent.setParams({
        	"comp" : component
        });
	compEvent.fire();
    }
})

Let us create a component in which the component we just created above is dynamically created, and also we will handle the event, for removing the component.

Component-

<!--ModalButton.cmp-->
<aura:component >
    <!-- 
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
     -->
    <ltng:require styles="{!$Resource.SLDS +'/assets/styles/salesforce-lightning-design-system-ltng.css'}"/>
    
    <!--handler for removing component-->
    <aura:handler name="RemoveComponent" action="{!c.removeComponent}" event="c:RemoveComponent"/>
	
    <div class="wk_static">
        <!--create component dynamically on button click-->
    	<button class="slds-button slds-button--neutral" onclick="{!c.getCompnent}">Open Modal</button>    
        
        <!--set component in the varible {!v.body}-->
        <div aura:id="cmpBody">
            {!v.body}
        </div>
    </div>
</aura:component>

Controller-

//ModalButtonController.js
({
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
    **/
	getCompnent: function(cmp,event) {
        //Create component dynamically
        $A.createComponent(
            "c:Modal",{},
            function(newcomponent){
                if (cmp.isValid()) {
                    var body = cmp.get("v.body");
                    body.push(newcomponent);
                    cmp.set("v.body", body);             
                }
            }            
        );
    },
    removeComponent:function(cmp,event){
        //get the parameter you defined in the event, and destroy the component
        var comp = event.getParam("comp");		
		comp.destroy();
    },
})

Output

Press Open Modal Button.

 create dynamic component

As you repeat the process of opening and closing the modal, it will seem as simple CSS display: block and display: none is applied. But on each “Open Modal” button click the modal component is created and on the “Close” buttons click the component is destroyed.

 

Support

That’s all for how to create dynamic components on a button Click in Lightning, still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/

 

Add Custom Row Action In Admin Controller Prestashop

$
0
0

When we create any admin controller in prestashop there we can have three only defined row action “View“, “Edit” and “Delete“. These row action can easily be create if we write $this->addRowAction(‘view’), $this->addRowAction(‘edit’), $this->addRowAction(‘delete’) because for this prestashop has already code for us. But what If you need to add some row action then ???

Here we will learn how we can add custom row action which is not defined by the prestashop.

Step : 1) Add customer row action like – $this->addRowAction(‘information’); . Here i’m trying to list information action in drop down in action column.

Step : 2) Now use a function

public function displayInformationLink()
{

}

In this function, you can use anything. Anything means to return any tpl file or you can perform PHP as well. This function may contain argument as well.

Like

public function displayInformationLink($token = null, $id, $name = null)
{
  // $token will contain token variable
  // $id will hold id_identifier value
  // $name will hold display name
}


Let me explain how this function work when we create custom row action in admin controller.

Whatever the row action you want to create just define it in $this->addRowAction(‘Your Desire Action name’);

Now call the function “displayActionNameLink()” this function has a prefix is display and suffix is link. Middle name contain you action name as we have used information. So function become

public function displayInformationLink() { }

Checkout the screenshot below. Before creating custom row action

Custom Row Action
After adding the custom row action –

Custom Row Action

Example code –

public function renderList()
    {
        $this->addRowAction('view');
        $this->addRowAction('delete');
        $this->addRowAction('information');
    }
}
public function displayInformationLink()
{
    return $this->context->smarty->fetch(_PS_MODULE_DIR_.'yourmodulename/views/templates/hook/information.tpl');
}

If there are something not understandable by this post then do comment below. We will surely assist on that.

 

Batch Apex Example In Salesforce

$
0
0

In this blog we will learn how to use Batch Apex. It is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Each time you invoke a batch class, the job is placed on the Apex job queue and is executed as a discrete transaction.

Advantages:

  • Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
  • If one batch fails to process successfully, all other successful batch transactions aren’t rolled back.

Key Points

  • To write a Batch Apex class, your class must implement the Database.Batchable interface and include the following three methods:
    • start()
    • execute()
    • finish()
  • If your code accesses external objects and is used in batch Apex, use Iterable<sObject> instead of Database.QueryLocator.
  • The default batch size is 200 record.

Apex Batch Class

Create an apex class which implements Database.Batchable interface and class must be globle like  mentioned below.

global class batchExample implements Database.Batchable<sObject> {}

Now describe all batchable class method i.e.

 global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
    }

    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    }    

    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    

Update Account Name

Account Name before executing batch class:

Here is the Batch class to update the account name.

global class batchExample implements Database.Batchable<sObject> {
    /**
        * Webkul Software.
        *
        * @category  Webkul
        * @author    Webkul
        * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
		* @license   https://store.webkul.com/license.html
	*/
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the batches of records or objects to be passed to execute
        
        String query = 'SELECT Id,Name FROM Account';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> accList) {
       
        // process each batch of records

        
        for(Account acc : accList)
        {        
           	// Update the Account Name 
            acc.Name = acc.Name + 'Webkul';
        }
        try {
        	// Update the Account Record
            update accList;
        
        } catch(Exception e) {
            System.debug(e);
        }
        
    }   
    
    global void finish(Database.BatchableContext BC) {
    	// execute any post-processing operations
  }
}

Run BATCHABLE Class  in Developer Console.

To invoke a batch class, simply instantiate it and then call Database.executeBatch with the instance:

batchExample be = new batchExample();
database.executeBatch(be);

You can also optionally pass a second scope parameter to specify the number of records that should be passed into the execute method for each batch.

batchExample be = new batchExample();
database.executeBatch(be,100);

Account Name after executing batch class:

Support

That’s all for how to use Batch Apex in Salesforce, still have any issue feel free to add a ticket and let us know your views to make the code better  https://webkul.uvdesk.com/en/customer/create-ticket/

Create Pie Chart using Visualforce page

$
0
0

Anyone who has used Salesforce must be knowing about Dashboard feature that is present in the CRM. This feature allows us to create charts for various sets of data like Sales per Account, or new Accounts by month. Any data for which a report could be generated, can be displayed as a chart.

Inspired from this feature, Salesforce developers around the globe started thinking about, if the dashboard can be displayed in a Visualforce page?

The Answer to this question sadly, is no. Although a Dashboard can be integrated in a Visualforce page, but for that we have to use an iFrame, and provide the id of that particular Dashboard to the iFrame url, for the Dashboard to be displayed on the Visualforce page. Which does not seem to be a very feasible option for the end user to work on.

However no one said that the similar chart cannot be created on the Visualforce page. That is right, Visualforce has predefined tag <apex:chart> which help us get a custom chart of the data we want to display.

Here in this blog, I am going to help you create a simple pie chart with the help of <apex:chart> to display the Draft/Activated orders ratio in a Visualforce page.

APEX Class

First of all we need to create a controller class in a salesforce org. For this tutorial, I am going to name the controller as PieChartController. In this class we are going to fetch the data of Orders and store it in other wrapper class. This wrapper class will be a part of our controller class.

The Wrapper class will look something like this:

public class PieData {

    public String name { get; set; }
    public Decimal data { get; set; }

    public PieData(String namevalue, Decimal datavalue) {
        name = namevalue;
        data = datavalue;
    }
}

Note that in this wrapper class there are two variable one which will hold the name, or we can say label of the pie slice, and the other, i.e. data, will tell the quantity which will be represented in the same chart.

Now that we have completed writing the wrapper class, lets move on to fetching the data and storing it in a wrapper class list variable.

Write a function named getOrderData, with the return type same as the wrapper class name, i.e. PieData. The result will look something like this:

public List getOrderData() {
    List data = new List();
        
    decimal draft=0,activated=0;
    draft       = [select count() from order where status = 'Draft'];
    activated   = [select count() from order where status = 'Activated'];
    data.add(new PieData('Activated ',activated));
    data.add(new PieData('Draft ',draft));
    return data;
}

In this class we have fetched the count of draft and activated orders, and then added that count to the wrapper class object data, with the corresponding label passed as hard-coded strings.
You can also keep the query in a try-catch block to ensure that the exception no object returned is handled, if there is no order for status either draft, or activated, however it is not required here as count will simply return 0 for such a case.

This completes our Controller class, yet a Visualforce page to display this data still needs to be written. So let’s go on to writing the code for the Visualforce page.

VISUALFORCE CODE

Create a Visualforce page with page controller set as the PieChartController. Then add the following code to the VF page:

<apex:chart data="{!OrderData}" height="400" width="400">
    <apex:pieSeries dataField="data"></apex:pieSeries>
</apex:chart>

All the attributes used in this code are required, and the page will not be saved without adding these attributes.

OUTPUT

Once you have written the code save and preview it to see the newly created vf page with a pie chart. The output will look something like this:

Pie Chart Output

More Pie Wedges can be added by adding data to the list of the wrapper class variable.

Click here to see a live demo of the output page.

SUPPORT

That’s all for how to create Pie Chart in Visualforce, for any further queries feel free to add a ticket at:

https://webkul.uvdesk.com/en/customer/create-ticket/

Or let us know your views on how to make this code better, in comments section below.


WordPress WooCommerce Event Manager

$
0
0

WordPress WooCommerce Event Manager facilitates the store owner to add events into the store. The admin can define the various type of tickets as well. He can add price and the quantity as well for the tickets. The user can synchronize the event to his Google Calendar also. A different page will be created where all the events will be listed.

Features of Event Manager

  • The store owner can add events into the store.
  • He can add different types of tickets and can define the price and quantity as well.
  • The user can synchronize the event details to his Google Calendar in a single click.
  • All the events will be listed under upcoming events.
  • The user can check the event location in Google Map in a single click.

Installation of Event Manager

The user will get a zip file which he has to upload in the “Add New” menu option in the WordPress admin panel. For this login to WordPress Admin Panel and Under the Dashboard hover your mouse over the “Plugins” menu option which brings out a Sub-Menu and then select the “Add New” option.

WordPress WooCommerce Event Manager

After this, you will see an option on the top of your page that is “Upload Plugin”, click the option to upload the zip file.

WordPress WooCommerce Event Manager

After clicking on the “Upload Plugin” option, below that you will see a button “Choose File” click on the button to browse for the zip file as per the snapshot below.

WordPress WooCommerce Event Manager

After browsing the file, click the “Install Now” button to install the plugin as per the snapshot.

WordPress WooCommerce Event Manager

Now when the plugin is installed correctly, you will see the success message and an option to activate the plugin. Click on “Activate Plugin” to activate the installed plugin.

WordPress WooCommerce Event Manager

Creating Project Credential

To use this plugin, you must have API Project Credentials. Google API Project Credentials are required to configure this plugin. Please click here to create a new project with your Gmail account.

1. After opening the page under “Credentials”. Please click “Create” button as shown in the below screenshot.

WordPress WooCommerce Event Manager

2. Enter the name of the project as you want to create.

WordPress WooCommerce Event Manager

3. Click “Create credentials” to choose the credential type.

WordPress WooCommerce Event Manager

4. Select “OAuth client ID” from the list.

WordPress WooCommerce Event Manager

5. Enter the Store URL and the redirect URL.

WordPress WooCommerce Event Manager

6. Copy credentials to enter into the configuration of the plugin. WordPress WooCommerce Event Manager

Configuration of Event Manager

After successful installation, the admin can configure this plugin under “WooCommerce > Event Settings”. Here the admin will enter the credentials to configure the Google Calendar Account.

 

Timezone : Select timezone from the dropdown.

Client id : Enter client id collected from the Google.

Client Secret : Enter client secret collected from Google.

Client Redirect URL : Enter redirect URL for the upcoming events of the website.

Admin End Management

After the successful installation of Event Manager, the admin of the store can add a new event by adding a new product. Here the admin needs to choose the product type as “E Tickets” and mark as Virtual Product. Here the admin enters the base price of the event.

Now under the “Inventory > Manage stock”  enable stock management at product level.

Under “E Ticket” the admin can configure the ticket as per the below screenshot:

Enable terms : Enable this option to display the terms and condition of the event.

Event Term : Enter the event term. Event term will be displayed on the front end as below image:

Event start time : Enter the start time of the event.

Event End time : Enter the end time of the event.

Event Location : Entr the location of the event.

Under “Custom Options” the admin can add various options with their price, stock, and the sort order.

Front End Workflow

On the front end, the customer can view all the events under the “Upcoming Events” menu like below snapshot.

The customer can view the location of the event by clicking the “View Location” in Google Map. 

And can add the event into the Google Calander by clicking the “Add Event”.

After that, by clicking the “Buy Ticket” the customer will be redirected to the event page. Over there he can choose the option as required and proceed to checkout.

That’s all for the WordPress WooCommerce Event Manager Plugin, still have any issue, feel free to add a ticket and let us know your views to make the plugin better at webkul.uvdesk.com

Calling Methods from XML data in Odoo

$
0
0

In the post, i will briefly tell about how to call methods while module installation using  XML <function /> tags in Odoo.

Sometime we required to perform some CURD operation automatically just after module installation , in this case  we can use the <function/> tags and call the method to perform these operations.

 

Create DEMO DATA File

First of all you need to create a xml file(let’s say demo.xml)  Like:

 

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data noupdate="1">
    </data>
</odoo>

Here noupdate is set to true for ensuring that on module update  this xml will not executed again and again.

It’s time to include your xml file in data or demo key of __mainifest__.py.

 

Calling Method Without parameters

Create a method in model  Like:

from odoo import api, fields, models
class product(models.Model):
	_inherit = "product.product"
	@api.model
	def oe_method_without_params(self):
		self.create(dict(name='demo.webkul.com'))

Now for calling this method   , create a <function/> tag in demo.xml Like:

 <function
    id="function_id"
    model="model_name"
    name="method_name"/>
 <function
    id="function_without_params"
    model="product.product"
    name="oe_method_without_params"/>

Now your demo.xml file will look like:

<odoo>
    <data noupdate="1">
        <function
            id="function_without_params"
            model="product.product"
            name="oe_method_without_params"/>
    </data>
</odoo>

Once module is installed this method(oe_method_without_params) will called.

Calling Method With  parameters

Include one more method in you python file:

@api.model
def oe_method_with_params(self,name,sale_ok=True):
    self.create(dict(name=name,sale_ok=sale_ok))

You python file will look like:

from odoo import api, fields, models
class product(models.Model):
	_inherit = "product.product"
        
	@api.model
	def oe_method_without_params(self):
		self.create(dict(name='demo.webkul.com'))
       
	@api.model
	def oe_method_with_params(self,name,sale_ok=True):
		self.create(dict(name=name,sale_ok=sale_ok))

Now for calling this method   , create a <function/> tag   and pass the params in  <value/> tags Like:

 <function
    id="function_id"
    model="model_name"
    name="method_name">
    <value>param1</value>
    <value>param2</value>
    ....
</function>
<function 
    id="function_with_params"
    model="product.product"
    name="oe_method_with_params">
        <value>erp.webkul.com</value>
      	<value>False</value>
</function>

Now your demo.xml file will look like:

<odoo>
    <data noupdate="1">
        <function
            id="function_without_params"
            model="product.product"
            name="oe_method_without_params"/>
        <function 
            id="function_with_params"
            model="product.product"
            name="oe_method_with_params">
                <value>erp.webkul.com</value>
      	        <value>False</value>
        </function>
    </data>
</odoo>

Once module is installed these method will called.

 

Hope  you enjoyed this post, I’d be very grateful if you’d write your opinions, comments and suggestions to keep the page updated and interesting.

You also like our post on working with xml data in odoo.

Working with XML data in Odoo

$
0
0

Odoo gives the developer several options  for working with data .

In this article, we will be looking at the XML data options in odoo.
We will study how to create , update and  delete the records using xml data.

 

Create DEMO DATA File

First of all you need to create a xml file(let’s say demo.xml)  Like:

 

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data noupdate="1">
    </data>
</odoo>

Here noupdate is set to true for ensuring that on module update  this xml will not executed again and again.

It’s time to include your xml file in data or demo key of __mainifest__.py.

Create  Records

For creating the record of model  , create a <record/> tag and place the fields Like:

<record model="model_name" id="record_id">
    <field name="field_name">field_data</field>
</record>


<record model="product.product" id="product_webkul">
    <field name="name">Webkul Product</field>
</record>

Now your xml file will look like:

<odoo>
    <data noupdate="1">
        <record model="product.product" id="product_webkul">
            <field name="name">Webkul Product</field>
        </record>
    </data>
</odoo>

Modify  Records

Some time you  may required to update the previously created record by other module.
For this create the record with  id (module_name.record_id) in your module like:

<record model="model_name" id="module_name.record_id">
    <field name="field_name">new_field_data</field>
</record>

<record model="product.product" id="product.service_order_01">
    <field name="name">Demo Product</field>
</record>

NOTE: you must place the module_name in depends of __mainifest__.py

Delete  Records

In case you want to delete the record , use <delete/> tag  along with id or search   like:

<delete model="model_name"   search="[('id','=',ref('module_name.record_id'))]"/>
<delete model="model_name" id="module_name.record_id"/>
<delete model="product.product" search="[('id','=', ref('product.service_order_01'))]"/>
<delete model="product.product" id="product.service_delivery"/>

While using  search you can specify  domain  on fields also like

<delete model="product.product" search="[('name','=','demo'),('sale_ok','=',False)]"/>

NOTE:

You must also place the module_name in depends  keys of __mainifest__.py.

Hope  you enjoyed this post, I’d be very grateful if you’d write your opinions, comments and suggestions to keep the page updated and interesting.

You also like our post on calling methods from xml in odoo.

WordPress WooCommerce Reward System

$
0
0

WordPress WooCommerce Reward System will engage store users for sales increment by assigning reward point to them. This plugin has a complete admin management so that admin can easily manage the reward points of buyers. It will enable a point-based loyalty program where frequent visitors earn points is a great way.

Reward System boosts the chance of turning the second sale from a first-time buyer. It will bump an existing customer into a higher paying bracket.

Features of WooCommerce Reward System

  • Reward point for new user registration, product purchase, and product review.
  • The admin can set the limit of reward point usage.
  • The admin can define the weightage of the reward points.
  • The admin can assign reward points manually to the buyer.
  • The admin can enter reward points for each product.
  • The buyer can see the details of earned reward points.
  • The buyer can enter the reward point at the time of checkout after which the amount relevant to the reward points will be deducted from product price.

Installation of WooCommerce Reward System

The user will get a zip file which he has to upload in the “Add New” menu option in the WordPress admin panel. For this login to WordPress Admin Panel and Under the Dashboard hover your mouse over the “Plugins” menu option which brings out a Sub-Menu and then select the “Add New” option.

WordPress WooCommerce Reward System

After this, you will see an option on the top of your page that is “Upload Plugin”, click the option to upload the zip file.

WordPress WooCommerce Reward System

After clicking on the “Upload Plugin” option, below that you will see a button “Choose File” click on the button to browse for the zip file as per the snapshot below.

WordPress WooCommerce Reward System

After browsing the file, click the “Install Now” button to install the plugin as per the snapshot.

Now when the plugin is installed correctly, you will see the success message and an option to activate the plugin. Click on “Activate Plugin” to activate the installed plugin.

WordPress WooCommerce Reward System

 

Configuration of WooCommerce Reward System

After the successful installation of the plugin, the admin can configure this under “WooCommerce > Settings > Rewards”.

Minimum Cart Amount :  The admin can define the minumum value of the cart total to award the reward points to the buyer.

Awarded Reward Points : Here the admin enters the reward points to be awarded after successful checkout with minimum cart total.

Reward Point Weightage : Value of each reward point.

Max. Reward Point Usage : Maximum reward point can be used per checkout.

Registration Reward Point : The admin can enable/disable the reward points per new buyer registration.

Awarded Reward Point : Numner of reward points awarded after successful registration.

Rating/Review Reward Point : The admin can enable/disable the reward points per new rating/review.

Awarded Reward Point : Number of reward points awarded when the buyer gives a new rating/review.

Multiple Reward Condition : The admin can choose whether he wants to award reward points on both the conditions matched, cart and product. Or only for any single condition.

Reward Point awarded on the basis of : Here the admin can select the basis to award reward points to the customer.

Admin End Workflow of WooCommerce Reward System

The admin can manage reward points manually of a buyer under “WooCommerce > Settings > Rewards > Manual Reward Transaction”.

Here the admin chooses the customer from the drop-down list for which he wants to debit/credit reward points.

Under “Products” admin can enable the reward points. Here admin can also define the minimum quantity and reward points of product to award to the buyer.

Front End Workflow of WooCommerce Reward System

On the front end, the user will get the notification on the registration page if enabled.

On the product page also the user get the notification about the reward points for product and review if enabled.

The buyer can use the available reward points at the checkout page.

Under “My account > Reward Point” the buyer can find all the details of available reward points and usage.

That’s all for the WordPress WooCommerce Reward System Plugin, still have any issue, feel free to add a ticket and let us know your views to make the plugin better at webkul.uvdesk.com

WordPress WooCommerce Marketplace Reward System

$
0
0

WordPress WooCommerce Marketplace Reward System allows the sellers to add reward points to their products using which customers can purchase the seller’s product. Here sellers can add reward points to each product.  Customers receive the reward points after the product purchase.

WordPress WooCommerce Marketplace Reward System is an add-on of WordPress WooCommerce Multi Vendor Marketplace Plugin. To use this plugin you must have installed first WordPress WooCommerce Multi Vendor Marketplace Plugin.

Features of Marketplace Reward System

  • The seller can enter reward points for each product.
  • Reward points of each seller are managed separately.
  • The admin can set the limit of reward point usage.
  • The admin can define the weightage of the reward points.
  • The admin can assign reward points manually to the buyer.
  • The buyer can see the details of earned reward points.
  • The buyer can enter the reward point at the time of checkout after which the amount relevant to the reward points will be deducted from product price.
  • Reward point for new user registration, product purchase, and product review.

Installation of Marketplace Reward System

The user will get a zip file which he has to upload in the “Add New” menu option in the WordPress admin panel. For this login to WordPress Admin Panel and Under the Dashboard hover your mouse over the “Plugins” menu option which brings out a Sub-Menu and then select the “Add New” option.

After this, you will see an option on the top of your page that is “Upload Plugin”, click the option to upload the zip file.

After clicking on the “Upload Plugin” option, below that you will see a button “Choose File” click on the button to browse for the zip file as per the snapshot below.

After browsing the file, click the “Install Now” button to install the plugin as per the snapshot.

Now when the plugin is installed correctly, you will see the success message and an option to activate the plugin. Click on “Activate Plugin” to activate the installed plugin.

Configuration of Marketplace Reward System

After the successful installation of the plugin, the admin can configure this under “WooCommerce > Settings > Rewards”.

Minimum Cart Amount :  The admin can define the minimum value of the cart total to award the reward points to the buyer.

Awarded Reward Points : Here the admin enters the reward points to be awarded after successful checkout with minimum cart total.

Reward Point Weightage : Value of each reward point.

Max. Reward Point Usage : Maximum reward point can be used per checkout.

Registration Reward Point : The admin can enable/disable the reward points per new buyer registration.

Awarded Reward Point : Numner of reward points awarded after successful registration.

Rating/Review Reward Point : The admin can enable/disable the reward points per new rating/review.

Awarded Reward Point : Number of reward points awarded when the buyer gives a new rating/review.

Multiple Reward Condition : The admin can choose whether he wants to award reward points on both the conditions matched, cart and product. Or only for any single condition.

Reward Point awarded on the basis of : Here the admin can select the basis to award reward points to the customer.

Admin End Workflow of Marketplace Reward System

The admin can manage reward points manually of a buyer under “WooCommerce > Settings > Rewards > Manual Reward Transaction”.

Here the admin chooses the customer from the drop-down list for which he wants to debit/credit reward points.

Seller End WorKflow of Marketplace Reward System

Under “Add Products” while adding a new product or under “Product List” the seller can enable the reward points. Here the seller can also define the minimum quantity and reward points of product to award to the buyer.

Front End Workflow of Marketplace Reward System

On the front end, the user will get the notification on the registration page if enabled.

On the product page also the user get the notification about the reward points for product and review if enabled.

The buyer can use the available reward points at the checkout page.

Under “My account > Reward Point” the buyer can find all the details of available reward points and usage.

That’s all for the WordPress WooCommerce Marketplace Reward System Plugin, still have any issue, feel free to add a ticket and let us know your views to make the plugin better at webkul.uvdesk.com

Page Object Model (POM) in Selenium

$
0
0

Selenium doesn’t inherently comes with any feature which provide any object management where we can manage the object information for a page and keep this object information outside the test script. Yes, it’s true, we can write the entire script for a page without a page object model and this could run through. This may state less pain to maintain the script only if we have limited testcases(say 5-10). Considering if we have thousands of testcases, is it easy to maintain the test script? We can’t change the whole testscript once the AUT goes certain changes or some modifications (which generally happens down the road).

So if the object info of a page change (the probability of which is higher) as the AUT undergoes changes with different release cycle, the impact of that change on the automation suite level is very high since the object info in the script is hard coded.

Why POM?

POM has nowadays become popular test automation design pattern around the testing industry. POM facilitates as to concentrate on testing the AUT rather than fixing the automation suite (the changed objects) to perform the test. In POM the Object information is managed outside the test script, thus making easy to understand the test script.

Advantages of POM

  1. It makes ease in maintaining the code (flow in the UI is separated from verification)
  2. Makes code readable (Methods get more realistic names)
  3. Makes the code reusable (object repository is independent of test cases)
  4. The Code becomes less and optimised

Implementation of POM

Let us consider a simple test scenario where we have an app with a login page, an account page and, say, home page.

The scenario be like

  • We go to the app url
  • Validate the app page is correct (home page)
  • We go to the login page and fill the form with a valid id and password
  • We validate if the account page opens

Now here we are dealing we three pages the home page, the login and the account page. Accordingly we create 3 POM classes, be like :

  • HomePage.java
  • LoginPage.java
  • MyAccountPage.java

Also we create a test class with the test script and names it as

  • TestLogin.java

HomePage.java

package pageModel;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class HomePage	{
	WebDriver driver;
	By homeHeading = By.xpath("//table//tr[3][@class='heading3']");
	By loginButton = By.id("login");
	public	HomePage(WebDriver driver)	{
		this.driver = driver;
	}
	//get the heading (the main heading which is present at the home page)
	public String getHomeHeading()	{
		String heading = driver.findElement(homeHeading).getText();
		return	heading;
	}
	public HomePage clickLoginButton()	{
		driver.findElement(loginButton).click();
		return	this;
	}
}

LoginPage.java

package pageModel;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage	{
	WebDriver driver;
	By username = By.id("email");
	By password = By.name("email");
	By submitButton = By.cssSelector("input[type='submit']");
	public	LoginPage(WebDriver driver)	{
		this.driver = driver;
	}
	public LoginPage usernameAs(String email)	{
		driver.findElement(username).sendKeys(email);
		return	this;
	}
	public LoginPage passwordAs(String pass)	{
		driver.findElement(password).sendKeys(pass);
		return	this;
	}
	public void	submit(){
		driver.findElement(submitButton).click();
	}
}

MyAccountPage.java

package pageModel;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class MyAccountPage	{
	WebDriver driver;
	// Declaring the xpath for the heading in By class
	By pageHeading = By.xpath("//table//tr[3][@class='heading3']");
	
	public	MyAccountPage(WebDriver driver)	{
		this.driver = driver;
	}
	//get the heading (username for which the account belongs to)
	public String getHeading()	{
		String heading = driver.findElement(pageHeading).getText();
		return	heading;
	}
}

TestLogin.java

package test;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import pageModel.*;

public class TestLogin {
	WebDriver driver;	
	@BeforeTest
	public void setUp() throws Exception {
	// setting the driver executable for chrome browser
		String chrome_path = System.getProperty("user.dir")+"/chromedriver";
		driver = new ChromeDriver();				// created a new instance for chrome driver
		driver.manage().window().maximize(); 
	}
	
	@AfterTest
	public void tearDown() throws Exception {
	    driver.quit();
	}

	@Test(priority=1)
	public void test() throws InterruptedException{
		driver.get("http://192.168.1.164:8080/home.html");
//		validate if we are at the home page
		String homeHeading = new HomePage(driver).getHomeHeading() ;
		Assert.assertEquals(homeHeading, "This is HOMEPAGE", "not at the home page");
//		redirect to the login page
		new HomePage(driver).clickLoginButton();
//		fill the login form
		new LoginPage(driver)
		.usernameAs("foo@bar.com")
		.passwordAs("secret")
		.submit();
//		check if redirected to account page with user name foo@bar.com
		String accountHeading = new HomePage(driver).getHomeHeading() ;
		Assert.assertEquals(accountHeading, "Welcome foo@bar.com ", "not at the account page");
	}
}

Now, if the AUT undergoes any change at the login page or at any page we just need to change the page object. Thus we don’t need to change our  test script again and again (even for the new release or built). The project structure will look like :

 

WordPress WooCommerce Marketplace Seller Coupons

$
0
0

WordPress WooCommerce Marketplace Seller Coupons allows the seller to generate coupons for their products. The seller can provide the discount to the customers with the help of a coupon code. The customer can use the coupon at the time of checkout and take the advantage of discount.

The coupon code will clearly identify who purchased items with a specific coupon code and can quickly identify the success or not of your promotion. It is proven that by adding coupons for discounts or free shipping will increase your conversion rate. If you are using special discounts in your traditional advertising, emails, direct mail, you will see a spike in traffic to these relevant pages.

WordPress WooCommerce Marketplace Seller Coupons is an add-on of WordPress WooCommerce Multi Vendor Marketplace Plugin. To use this plugin you must have installed first WordPress WooCommerce Multi Vendor Marketplace Plugin.

Features of Marketplace Seller Coupons

  • Allows the seller to generate coupons for their products.
  • The seller can set how many times a coupon can be used.
  • The seller can set how many times a customer can use the coupon.
  • The seller can set how many times a coupon will be applied to a product.
  • The seller can define the minimum and the maximum cart total to use the coupon.
  • The seller can allow selected customers to use the coupon.
  • The seller can restrict any specific email as well to use the coupon.
  • The seller can allow a coupon for specific product and category.
  • The seller can check the coupon history.
  • Buyers can use the coupon at the checkout and avail the benefits of coupon.

Installation of Marketplace Seller Coupons

The user will get a zip file which he has to upload in the “Add New” menu option in the WordPress admin panel. For this login to WordPress Admin Panel and Under the Dashboard hover your mouse over the “Plugins” menu option which brings out a Sub-Menu and then select the “Add New” option.

After this, you will see an option on the top of your page that is “Upload Plugin”, click the option to upload the zip file.

After clicking on the “Upload Plugin” option, below that you will see a button “Choose File” click on the button to browse for the zip file as per the snapshot below.

After browsing the file, click the “Install Now” button to install the plugin as per the snapshot.

Now when the plugin is installed correctly, you will see the success message and an option to activate the plugin. Click on “Activate Plugin” to activate the installed plugin.

Seller End workflow of Marketplace Seller Coupons

After successful installation of the plugin, the seller can create and manage coupons under “Manage Coupons > Add Coupon”. 

Coupon Code : Code used by the customer to apply the coupon. Must be unique as it’s used as an identifier.

Description : Info about the coupon, e.g., Dates in effect, promotion, compensation, ticket number. For internal use.

Under Coupon Data the seller will configure the coupon.

Discount Type : Seller select the type of discount to be applied to the coupon. Whether it is Percentage Discount, Fixed Cart Discount or Fixed Product Discount.

  • Percentage discount – A percentage discount for the entire cart. For example, if the cart contains three (3) t-shirts @ $20 each = $60, a coupon for 10% off applies a discount of $6.
  • Fixed cart discount – A fixed total discount for the entire cart. For example, if the cart contains three (3)  t-shirts @ $20 each = $60, a coupon for $10 off gives a discount of $10.
  • Fixed product discount – A fixed total discount for selected products only. The customer receives a set amount of discount per item. For example, three (3) t-shirts @ $20 each with a coupon for $10 off applies a discount of $30.

Coupon Amount : Fixed value or percentage, depending on the discount type you choose. Entered without a currency unit or a percent sign, which are added automatically, e.g., Enter ’10’ for £10 or 10%.

Coupon Expiry Date : Date the coupon should expire and can no longer be used. Expiry happens at 12:00 am or 00:00 on the date chosen. If you want a coupon to be valid through Christmas Day but invalid the moment Christmas is over, set the expiration date to YYYY-12-26 as it will expire on YYYY-12-26 00:00. It uses your site’s time zone setting at Settings > General > Timezone in WordPress.

Minimum spend : Allows you to set the minimum subtotal needed to use the coupon.  Note: The sum of the cart subtotal + tax is used to determine the minimum amount.

Maximum spend :  Allows you to set the maximum subtotal allowed when using the coupon.

Individual use only : Tick the box if you don’t want this coupon to be used in combination with other coupons.

Exclude sale items :  Tick the box if you don’t want this coupon to apply to products on sale. Per-cart coupons do not work if a sale item is added afterward.

Products :  Products that the coupon will be applied to, or that need to be in the cart in order for the “Fixed cart discount” to be applied.

Exclude products :  Products that the coupon will not be applied to, or that cannot be in the cart in order for the “Fixed cart discount” to be applied.

Product categories :  Product categories that the coupon will be applied to, or that need to be in the cart in order for the “Fixed cart discount” to be applied.

Exclude categories :  Product categories that the coupon will not be applied to, or that cannot be in the cart in order for the “Fixed cart discount” to be applied.

Email restrictions :  Email address or addresses that can use a coupon. Verified against customer’s billing email.

NOTE : Leaving “Products” and “Exclude Products” blank allows the coupon to be applied to the entire store.

Usage limit per coupon : How many times a coupon can be used by all customers before being invalid.

Limit usage to X items :  How many items the coupon can be applied to before being invalid. This field is only displayed if there are one or more products that the coupon can be used with, and is configured under the Usage Restrictions. (Note: Option is only available if you are creating a Product Discount coupon.)

Usage limit per user :  How many times a coupon can be used by each customer before being invalid for that customer.

The seller can track the coupon usage under the coupon list and can edit or delete the coupon as well.

Front End Workflow of Marketplace Seller Coupons

The customer can use the coupon at the time of checkout. And the discount will be applied if the coupon code is valid and match all the conditions.

The applied discount will be available in the order details as well.

That’s all for the WordPress WooCommerce Marketplace Seller Coupons Plugin, still have any issue, feel free to add a ticket and let us know your views to make the plugin better at webkul.uvdesk.com


Exception Handling In Lightning Component

$
0
0

 What is Exception and Exception Handling?

Exception is an event which occur during execution of  program instruction and disrupts the normal flow of program instructions. Exception handling is a mechanism to handle exception so that normal flow of program should be maintained.

In this blog we will learn about Exception Handling In Lightning Component.  Follow the steps mentioned below.

Steps:

1). Create the lightning component to show the exception.

<-- errorComponent -->
<aura:component>
<!-- 
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */
 -->	
    <aura:attribute name="errorMsg" type="String"></aura:attribute>
    <aura:attribute name="title" type="String"></aura:attribute>
    <div class="wk_model_bg"></div>
    <section role="dialog"  aria-labelledby="header" aria-describedby="errMsg" class="slds-modal slds-fade-in-open">
        <div class="slds-modal__container " aura:id="ErrorBox" >
            <div class="slds-modal__header" aura:id ="errHeader">
                <lightning:buttonIcon aura:id="clsBtn" iconName="utility:close" alternativeText="Close" class="slds-button slds-button--neutral slds-p-horizontal--xx-small slds-m-right--x-small slds-float--right" onclick="{!c.myAction}">     
                </lightning:buttonIcon> 
                <h2 id="header" class="slds-text-heading--medium wk_text">{!v.title}</h2>
            </div>
            <div class="myAction slds-p-around--large" aura:id ="errMsg" style="background:#f4f6f9">
                {!v.errorMsg}
            </div>
        </div>
    </section>
    
</aura:component>

2). Create a client site controller for errorComponent.

({
   /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */
	myAction : function(component, event, helper) {
        component.destroy();
    }
})

3). Here is code for button which action is to delete Account record which can not be deleted because it is associated with the case.

<!-- deleteAccount -->
<!-- 
/**
* Webkul Software.
*
* @category  Webkul
* @author    Webkul
* @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
* @license   https://store.webkul.com/license.html
*/
-->

<aura:component controller = "accListJsClass">
      <div aura:id="errorDialogPlaceholder" >
    	{!v.body}
      </div>
        <div class="slds-col slds-size_1-of-8 allBtn">
            <lightning:button label="Delete Account"
                                     iconName="utility:delete"
                                     iconPosition="left"
                                     variant="destructive"
                                     onclick="{!c.deleteSlctd}">
            </lightning:button>
        </div>
</aura:component>

4).Create a client site controller for deleteAccount.

({
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
        deleteSlctd : function(component,event,helper) {
        var getCheckAllId = component.find("cboxRow");
        var selctedRec = [];
        for (var i = 0; i < getCheckAllId.length; i++) {
            
            if(getCheckAllId[i].get("v.value") == true )
            {
                selctedRec.push(getCheckAllId[i].get("v.text")); 
            }
        }
        helper.deleteSelected(component,selctedRec);
    }
})

5). Create a Helper for deleteAccount.

({
   /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */
    deleteSelected : function(component,selctedRec){
        var action = component.get("c.delSlctRec");
        action.setParams({
            "slctRec": selctedRec
        });
        action.setCallback(this, function(response){
            var state =  response.getState();
            if(state == "SUCCESS")
            {
                var errorMsg = "Successfully Deleted";
                var error = "Success";
                $A.createComponent(
                    "c:errorComponent",
                    {
                      "errorMsg": errorMsg,
                        "title" : error
                     },
                    function(errComponent){
                        if (component.isValid()) {
                            var targetComp = component.find("errorDialogPlaceholder");
                            var body = component.get("v.body");
                            body.push(errComponent);
                            component.set("v.body", body);             
                        }
                    }            
                );
            } else if (state=="ERROR") {
                var errorMsg = action.getError()[0].message;
                console.log(errorMsg);
                var error = "Error";
                $A.createComponent(
                    "c:errorComponent",
                    {
                      "errorMsg": errorMsg,
                        "title" : error
                     },
                    function(errComponent){
                        if (component.isValid()) {
                            var targetComp = component.find("errorDialogPlaceholder");
                            var body = component.get("v.body");
                            body.push(errComponent);
                            component.set("v.body", body);             
                        }
                    }            
                );
            }
        });
        $A.enqueueAction(action);
    }
})

6). Create apex class to perform the delete operation.

public class accListJsClass{
    /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */

    @AuraEnabled 
    public List<Account> delRec = new List<Account>();
    
    @AuraEnabled 
    public static List<Account> delSlctRec(List<String> slctRec)
    {
        accListJsClass alc = new accListJsClass();
        // Id is for demo purpose only 
        alc.delRec = [SELECT Id FROM Account WHERE Id = '0017F000006PUEaQAO' ]; 
        try{
           delete alc.delRec;
        } catch(Exception ex)
        {
            throw new AuraHandledException(ex.getMessage());
        }
       
    }
}

Output:

For pagination in lightning component Click Here.

For mass delete in lightning component Click Here.

To create Dynamic Component on button click Click Here.

 

Support:

That’s all for Exception Handling in lightning component, still if you have any further query or seek assistance to make your salesforce classic apps compatible with lightning experience, feel free to add a ticket, we will be happy to help you https://webkul.uvdesk.com/en/customer/create-ticket/.

 

Parsing XML file data in APEX

$
0
0

If you are a web developer then chances are that you must have used XML. In fact, even non developers have heard about it. It has been a general format for storing, sending and receiving data in the software Industry. Even with other format like JSON slowly taking it’s own place for getting the same job done, XML still works as the only method for many API response. We can simply generate and parse XML file to contain data.

Different platforms give us their own way of generating and parsing XML, and likewise APEX is no exception. Any Salesforce developer who is working with external API calls must have encountered the problem of parsing an XML file, at some point in their career.

Now if we look at an XML file it seems like all jumbled up data which is hardly readable by human eyes, let alone a machine. How can we code to parse an XML file? Well the data is not as much jumbled as you think and even parsing an XML file in APEX is not too complex of a task. Let’s see how can we parse XML with the predefined classes of APEX.

Dummy XML data

First thing first, we’ll be needing XML data to parse, so let’s take some dummy XML data.

<?xml version="1.0" encoding="UTF-8"?>
<products>
	<product>
		<name>Xbox</name>
		<code>XBO</code>
	</product>
	<product>
		<name>Playstation</name>
		<code>PS</code>
	</product>
	<product>
		<name>Wii</name>
	</product>
</products>

In the above XML data we can see that there are various tags. The first tag being an XML tag. This tag tells that the document is an XML document. Moving on we have products, which is a root tag. Every XML document has only one root tag. Next we have multiple product tags, which shows that this is carrying an array of products.

Each array has it’s own child nodes, name and code. The data filled in one product tag is the data of that product in the array and each child node corresponds to the label of the data it is carrying. This brings us to the actual data, which is stored in the tags.

APEX Code

public class XMLparse{
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     **/
    string XMLString;
    public list pro;
    product2 temppro;
    
    public XMLparse(){
        pro = new list();
        XMLString = '<?xml version="1.0" encoding="UTF-8"?><products><product><name>Xbox</name><code>XBO</code></product><product><name>Playstation</name><code>PS</code></product><product><name>Wii</name></product></products>';
        DOM.Document doc=new DOM.Document();
        try{
            doc.load(XMLString);
            DOM.XmlNode rootNode=doc.getRootElement();
            parseXML(rootNode);
            pro.add(temppro);
            insert pro;
        }catch(exception e){
            system.debug(e.getMessage());
        }
    }
    
    private void parseXML(DOM.XMLNode node) {
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
        system.debug(node.getName());
            if(node.getName()=='product'){
                if(temppro!=null)
                    pro.add(temppro);
                temppro = new product2();
            }
            if(node.getName()=='name')
                temppro.name=node.getText().trim();
            if(node.getName()=='code')
                temppro.productcode=node.getText().trim();
        }
        for (Dom.XMLNode child: node.getChildElements()) {
            parseXML(child);
        }
    }
}

In the above class we can see that there are two functions, one constructor to the class and the other which actually parses the XML data. The XML string is fed to the DOM.Document class object which construct a document object for this XML class. Once it is dome we are going to get the root element of the XML file with the help of getRootElement function of DOM.Document class and feed it to the XmlNode class object.

This node object will become an argument for the parseXML function and hence we are going to call that function to initiate the main part. The getName() function will return the name of the element like, <name> will return name while the node.getText() function will return the content of that tag.

node.getChildElelement() will return all the child elements of a tag. The return type of getText() function is string so the data will always be in string format. If you want to convert it to any other type you can use the valueOf function of that class.

After the successful execution of this class the control will return to the constructor and it will call the insert command.

Output

To test this class you can either create a VF page and add the controller of that VF page as this class, or you can simply create an object of this class in Anonymous Window from Developer Console. Soon after you will do this the updates will be visible to you in products as three new products will be added from the XML data.

Here I have executed the code via the Anonymous Window from Developer Console and the result was:

New Product Output

SUPPORT

That’s all for how parse XML data in Apex, for any further queries feel free to add a ticket at:

https://webkul.uvdesk.com/en/customer/create-ticket/

Or let us know your views on how to make this code better, in comments section below.

Protected: Odoo POS Manage Order Selector

$
0
0

This content is password protected. To view it please enter your password below:

Remote Action function in Visualforce Page

$
0
0

In this blog, we will learn Remote Action function in Visualforce Page. First of all, we should know, what is remote action function in salesforce. Let’s get started!

What is Remote Action function in Salesforce?

Remote action function in salesforce allows a user to access any method from any class through javasrcipt methods, and get the result as a javascript object for further manipulation.

Points to remember while implementing remote action function:

  • Remote action method should have @RemoteAction annotation.
  • The method should also be Global and Static

Implementation

Let us start with controller code:

global with sharing class ContactJs {  
    /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */
    public ContactJs() { } // empty constructor    

    @RemoteAction //the function to be called in remote action should use this annotation
    global static list<Contact> getcon() {
        //function should be static and global else it will throw error
        list<Contact> con1 = [SELECT id,name FROM contact limit 5];
        if(con1!=null && !con1.isEmpty()){        
            return con1;        
        }else{        
            return  new list<contact>();        
        }
    }
}

Now the Visualforce Page:

<apex:page controller="ContactJs">
    <!-- 
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
     -->
    <script type = "text/javascript">
    function getRemoteContact() {
        var a;
        Visualforce.remoting.Manager.invokeAction(
            //Invoking controller action getcon
            '{!$RemoteAction.ContactJs.getcon}',
            
            function(result, event){
               //We can access the records through the parameter result
               //event.status determines if there is error or not 
               if(event.status){
                    document.getElementById('remoteContactId').innerHTML = 'Contact Name: <br/><br/>';
                    for(a=0;a<result.length;a++){                        
                        document.getElementById('remoteContactId').innerHTML +=  result[a].Name +'<br/>';                    
                    }                                       
               }               
            },
            {escape: true}
        );
    }
    </script>

    <button onclick="getRemoteContact()">Get Contact</button>
    <div id="responseErrors"></div>
    <apex:pageBlock id="block">        
        <apex:pageBlockSection id="blockSection" columns="2">
                <span id="remoteContactId"></span>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Output

Here is the output:

Support

That’s all for Remote Action function in Visualforce Page Click in Lightning, still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/

 

Add Product Tab For Specific Product Type In Your Custom Module Magento 2

$
0
0

Add Product Tab For Specific Product Type In Your Custom Module Magento 2 – Here I’m going to explain you how you can add custom product tab for specific product type in your custom module.
STEP – 1

  1. Create “catalog_product_simple.xml” File. // If you want to show that tab for “simple” product type.
  2. Create “catalog_product_configurable.xml” File. // If you want to show that tab for “configurable” product type.
  3. Create “catalog_product_grouped.xml” File. // If you want to show that tab for “grouped” product type.
  4. Create “catalog_product_virtual.xml” File. // If you want to show that tab for “virtual” product type.
  5. Create “catalog_product_bundle.xml” File. // If you want to show that tab for “bundle” product type.
  6. Create “catalog_product_downloadable.xml” File. // If you want to show that tab for “downloadable” product type.
  7. Create “catalog_product_new.xml and catalog_product_new.xml” File. // If you want to show that tab for all product type.

In File Location Vendor/CustomModule/view/adminhtml/layout.

STEP-2
Add below code.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product_form">
            <block class="Vendor\CustomModule\Block\Adminhtml\Catalog\Product\Edit\Tab\CustomTab" name="custom.tab">
                <arguments>
                    <argument name="config" xsi:type="array">
                        <item name="label" xsi:type="string" translate="true">Custom Tab</item>
                        <item name="collapsible" xsi:type="boolean">true</item>
                        <item name="opened" xsi:type="boolean">true</item>
                        <item name="sortOrder" xsi:type="string">2</item>
                        <item name="canShow" xsi:type="boolean">true</item>
                        <item name="componentType" xsi:type="string">fieldset</item>
                    </argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

STEP-3
Now create file “CustomTab.php” in location Vendor\CustomModule\Block\Adminhtml\Catalog\Product\Edit\Tab

<?php
namespace Vendor\CustomModule\Block\Adminhtml\Catalog\Product\Edit\Tab;
 
class CustomTab extends \Magento\Framework\View\Element\Template
{
    /**
     * @var string
     */
    protected $_template = 'customtab.phtml';
 
}

STEP-4
In last create template file “customtab.phtml” in loction Vendor/CustomModule/view/adminhtml/templates

Custom tab content...................

downloadable-product-tab

In this way you can add tabs for specific type product and If you have any query then write comment below.

Viewing all 5480 articles
Browse latest View live