Tuesday 30 July 2019

How to make auto select first child product of configurable product in magento2?


Override this file to your theme:
vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js

your theme file location will be:
app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js

_fillSelect: function (element) {
    var attributeId = element.id.replace(/[a-z]*/, ''),
        options = this._getAttributeOptions(attributeId),
        prevConfig,
        index = 1,
        allowedProducts,
        i,
        j;

    this._clearSelect(element);
    element.options[0] = new Option('', '');
    element.options[0].innerHTML = this.options.spConfig.chooseText;
    prevConfig = false;

    if (element.prevSetting) {
        prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
    }

    if (options) {
        for (i = 0; i < options.length; i++) {
            allowedProducts = [];
            if (prevConfig) {
                for (j = 0; j < options[i].products.length; j++) {
                    // prevConfig.config can be undefined
                    if (prevConfig.config &&
                        prevConfig.config.allowedProducts &&
                        prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                        allowedProducts.push(options[i].products[j]);
                    }
                }
            } else {
                allowedProducts = options[i].products.slice(0);
            }

            if (allowedProducts.length > 0) {
                options[i].allowedProducts = allowedProducts;
                element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
                if (typeof options[i].price !== 'undefined') {
                    element.options[index].setAttribute('price', options[i].prices);
                }

                element.options[index].config = options[i];




                index++;
            }
            // Code added to select option
            if (i == 0) {
                this.options.values[attributeId] = options[i].id;
            } 
        }
        //Code added to check if configurations are set in url and resets them if needed
        if (window.location.href.indexOf('#') !== -1) {this._parseQueryParams(window.location.href.substr(window.location.href.indexOf('#') + 1));}
    }

},

===================================================================
For Swatch: Override the below file to your theme

/module-swatches/view/frontend/web/js/SwatchRenderer.js

_RenderControls: function () {
    var $widget = this,
        container = this.element,
        classes = this.options.classes,
        chooseText = this.options.jsonConfig.chooseText,
        selectedArray = []; // Variable declation for autoselect element array

    $widget.optionsMap = {};

    $.each(this.options.jsonConfig.attributes, function () {
        var item = this,
            controlLabelId = 'option-label-' + item.code + '-' + item.id,
            options = $widget._RenderSwatchOptions(item, controlLabelId),
            select = $widget._RenderSwatchSelect(item, chooseText),
            input = $widget._RenderFormInput(item),
            listLabel = '',
            label = '';

        // Show only swatch controls
        if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id)) {
            return;
        }

        if ($widget.options.enableControlLabel) {
            label +=
                '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
                    item.label +
                '</span>' +
                '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';
        }

        if ($widget.inProductList) {
            $widget.productForm.append(input);
            input = '';
            listLabel = 'aria-label="' + item.label + '"';
        } else {
            listLabel = 'aria-labelledby="' + controlLabelId + '"';
        }

        // Create new control
        container.append(
            '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
                 'attribute-code="' + item.code + '" ' +
                 'attribute-id="' + item.id + '">' +
                label +
                '<div aria-activedescendant="" ' +
                     'tabindex="0" ' +
                     'aria-invalid="false" ' +
                     'aria-required="true" ' +
                     'role="listbox" ' + listLabel +
                     'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
                    options + select +
                '</div>' + input +
            '</div>'
        );

        $widget.optionsMap[item.id] = {};

        // Aggregate options array to hash (key => value)
        $.each(item.options, function () {
            if (this.products.length > 0) {
                $widget.optionsMap[item.id][this.id] = {
                    price: parseInt(
                        $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
                        10
                    ),
                    products: this.products
                };
            }
        });
        //Create array for Autoselect swatch
        selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
    });


    // Connect Tooltip
    container
        .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
        .SwatchRendererTooltip();

    // Hide all elements below more button
    $('.' + classes.moreButton).nextAll().hide();

    // Handle events like click or change
    $widget._EventListener();

    // Rewind options
    $widget._Rewind(container);

    //Emulate click on all swatches from Request
    $widget._EmulateSelected($.parseQuery());
    $widget._EmulateSelected($widget._getSelectedAttributes());

    //Trigger click for Autoselect first option swatch
    $.each(selectedArray, function () {
        if(this != undefined) this.click();
    });

},


Friday 26 July 2019

How to create a new administrator account through SSH in Magento 2

php bin/magento admin:user:create --admin-user='ayurvuser' --admin-password='admin#123' --admin-email='admin@ytd.com' --admin-firstname='Test' --admin-lastname='Tester'

Monday 15 July 2019

Magento 2 folder/file permissions command line

You should set as bellow recommended.

cd <your Magento install dir>

find . -type f -exec chmod 644 {} \;                        // 644 permission for files

find . -type d -exec chmod 755 {} \;                        // 755 permission for directory

find ./var -type d -exec chmod 777 {} \;                // 777 permission for var folder   

find ./pub/media -type d -exec chmod 777 {} \;

find ./pub/static -type d -exec chmod 777 {} \;

chmod 777 ./app/etc

chmod 644 ./app/etc/*.xml

chown -R :<web server group> .

Wednesday 10 July 2019

How to get USPS Shipping API (Shipping price) with PHP

<?php
function USPSParcelRate($weight,$dest_zip,$origin_zip ,$pack_size="REGULAR",$userName,$servicecode) {
// =============== DON'T CHANGE BELOW THIS LINE API CALL===============
$url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=<RateV4Request USERID=\"$userName\"><Package ID=\"1ST\"><Service>ALL</Service><ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$weight</Pounds><Ounces>0</Ounces><Container/><Size>$pack_size</Size><Machinable>FALSE</Machinable></Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
// echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see the full array
return $params['RATEV3RESPONSE']['1ST'][$servicecode]['RATE'];
}

$res = USPSParcelRate($weight,$dest_zip,$origin_zip ,"REGULAR",$userName,$servicecode);

echo "Price ".$res;
?>

Monday 8 July 2019

how to password protected in htaccess url in pacific country ?

.htaccess

File content:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home2/b4x4u4fu/public_html/.htpasswd
require valid-user
Order allow,deny
Allow from all
deny from 1.6.0.0/1

command line run : htpasswd -c .htpasswd [username]

how to password protected in php url in pacific country ?

/* ------------------------------ */

function ip_visitor_country()
{

    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);

    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see stackoverflow.com/questions/3110487/

    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
    }

    return $country;
}

$ip =trim(ip_visitor_country());

if($ip=='India'){

    function CheckAccess()

{

  $result = (isset($_SERVER['PHP_AUTH_USER']) &&

            $_SERVER['PHP_AUTH_USER'] == 'admin' &&

            $_SERVER['PHP_AUTH_PW'] == 'admin@123');

  if (!$result)

  {

   header('WWW-Authenticate: Basic realm=“Test restricted area”');

   header('HTTP/1.0 401 Unauthorized');

   return false;

  }

  else

   return true;

}


if (!CheckAccess())

{

  //show the access denied message and exit script

  echo 'Access denied!';

  exit;

}

}

//exit;
/* ------------------------------------- */