Using Docker I get the error: “SQLSTATE[HY000] [2002] No such file or directory”

If you face this error on your local then you need to change your DB configuration to run the project on local with docker.

Your docker config file might look like

version: '2'

services:
  web:
    build: ./docker/php
    ports:
      - 80:80
    volumes:
      - .:/var/www/html/
    links:
      - db
  db:
    build: ./docker/mysql
    ports:
      - 3306

In above settings (db:) this is your localhost so your database configuration will look like
database host: db
database username: root
database password : 12345

In short, you need to replace “localhost” with “db” and it’s done.

Argument 1 passed to App\Service\FileUploader::upload() must be an instance – symfony 4

If you face “Argument 1 passed to App\Service\FileUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, ” this error while playing with files in Symfony 4. Then you need to change your file field in controller as. Change your code from

$file = $task->getTaskLogo(); 
to
$file = $form['task_logo']->getData();
. Where task_logo is the name of the file field of your form.

 

 

 

 

Points to keep in mind while developing custom form in Magento 2 module on admin end.

Two things keep in mind


1) Form action could be defined as

<?php echo $this-&gt;getUrl("pilot_smile/options/save"); ?>;
2) Do not forget to add form_key else you would be going to waste your several hours on finding the dashboard redirection issue on form submission.
<input name="form_key" type="hidden" value="<?php echo $block->getFormKey()?>" />;

 

 

UI Component Listing And Not registered handle in Magento2

If you face below error in your Magento 2 custom module.

Not registered handle [namespace]_[module]_team_index_data_source

There is one reason for above error is that you are missing di.xml file from [namespace]_[module]/etc/ folder

Copy the following code into di.xml file and place it in root of the etc folder of your module. Don’t forget to change the namespace and module name according to your module in the code.


<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments>
<argument name="collections" xsi:type="array">
...
<item name="[namespace]_[module]_team_index_data_source" xsi:type="string">[Namespace]\[Module]\Model\ResourceModel\Team\Collection</item>
...
</argument>
</arguments>
</type>

Happy coding 🙂

Load More posts feature in WordPress

Copy below code into your functions.php


function misha_paginator( $first_page_url ){

// the function works only with $wp_query that's why we must use query_posts() instead of WP_Query()
global $wp_query;

// remove the trailing slash if necessary
$first_page_url = untrailingslashit( $first_page_url );


// it is time to separate our URL from search query
$first_page_url_exploded = array(); // set it to empty array
$first_page_url_exploded = explode("/?", $first_page_url);
// by default a search query is empty
$search_query = '';
// if the second array element exists
if( isset( $first_page_url_exploded[1] ) ) {
$search_query = "/?" . $first_page_url_exploded[1];
$first_page_url = $first_page_url_exploded[0];
}

// get parameters from $wp_query object
// how much posts to display per page (DO NOT SET CUSTOM VALUE HERE!!!)
$posts_per_page = (int) $wp_query->query_vars['posts_per_page'];
// current page
$current_page = (int) $wp_query->query_vars['paged'];
// the overall amount of pages
$max_page = $wp_query->max_num_pages;

// we don't have to display pagination or load more button in this case
if( $max_page <= 1 ) return;

// set the current page to 1 if not exists
if( empty( $current_page ) || $current_page == 0) $current_page = 1;

// you can play with this parameter - how much links to display in pagination
$links_in_the_middle = 4;
$links_in_the_middle_minus_1 = $links_in_the_middle-1;

$first_link_in_the_middle = $current_page - floor( $links_in_the_middle_minus_1/2 );
$last_link_in_the_middle = $current_page + ceil( $links_in_the_middle_minus_1/2 );

// some calculations with $first_link_in_the_middle and $last_link_in_the_middle
if( $first_link_in_the_middle <= 0 ) $first_link_in_the_middle = 1;
if( ( $last_link_in_the_middle - $first_link_in_the_middle ) != $links_in_the_middle_minus_1 ) { $last_link_in_the_middle = $first_link_in_the_middle + $links_in_the_middle_minus_1; }
if( $last_link_in_the_middle > $max_page ) { $first_link_in_the_middle = $max_page - $links_in_the_middle_minus_1; $last_link_in_the_middle = (int) $max_page; }
if( $first_link_in_the_middle <= 0 ) $first_link_in_the_middle = 1;

// begin to generate HTML of the pagination
$pagination = '<nav id="misha_pagination" class="navigation pagination" role="navigation">
<div class="older">';

if( $current_page < $max_page )
$pagination.= '<a title="Read More" id="misha_loadmore">Read More <i class="fa fa-angle-double-right"></i> </a> ';
$pagination.= "</div></nav>\n";
echo str_replace(array("/page/1?", "/page/1\""), array("?", "\""), $pagination);
}
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');

// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );

wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'first_page' => get_pagenum_link(1)
) );

wp_enqueue_script( 'my_loadmore' );
}

add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );

function misha_loadmore_ajax_handler(){

$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );

if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part('content', 'grid');
endwhile;

endif;
die;
}

add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

 

JS code to send Ajax call and recieve response

<script type="text/javascript">
jQuery(function($){
$('body').on('click', '#misha_loadmore', function(){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data : {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page,
'first_page' : misha_loadmore_params.first_page // here is the new parameter
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#misha_loadmore').text('Loading...');
},
success : function( data ){
$('ul.sp-grid').append(data);
//$('#misha_pagination').remove();
$('#misha_loadmore').html('Read More <i class="fa fa-angle-double-right"></i>');
misha_loadmore_params.current_page++;
}
});
return false;
});
});
</script> 

 

Finally html button which will be clicked to load more posts again and again.

<?php misha_paginator( get_pagenum_link() ); ?>

Code to generate Stripe token for testing purpose

Code to generate Stripe token for testing purpose

<html>
  <head>
    <title>create stripe  token in js</title>
    <script src="https://js.stripe.com/v3/"></script>
    <style type="text/css">
  
  .StripeElement {
    background-color: white;
    height: 40px;
    padding: 10px 12px;
    border-radius: 4px;
    border: 1px solid transparent;
    box-shadow: 0 1px 3px 0 #e6ebf1;
    -webkit-transition: box-shadow 150ms ease;
    transition: box-shadow 150ms ease;
  }

  .StripeElement--focus {
    box-shadow: 0 1px 3px 0 #cfd7df;
  }

  .StripeElement--invalid {
    border-color: #fa755a;
  }

  .StripeElement--webkit-autofill {
    background-color: #fefde5 !important;
  }

    </style>    
  </head>
  <body>
    <form action="/charge" method="post" id="payment-form">
        <div class="form-row">
          <label for="card-element">
            Credit or debit card
          </label>
          <div id="card-element">
            <!-- a Stripe Element will be inserted here. -->
          </div>

          <!-- Used to display form errors -->
          <div id="card-errors" role="alert"></div>
        </div>

        <button>Submit Payment</button>
      </form>    
      <textarea style="width:400px; height:200px;" id="stripeToken" placeholder="Stripe token will print here."></textarea>


      <script type="text/javascript">
       // Create a Stripe client
      var stripe = Stripe('pk_test_xpuKHHXWfW9eUw6DlmNZQI5N');

      // Create an instance of Elements
      var elements = stripe.elements();

      // Custom styling can be passed to options when creating an Element.
      // (Note that this demo uses a wider set of styles than the guide below.)
      var style = {
        base: {
          color: '#32325d',
          lineHeight: '18px',
          fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
          fontSmoothing: 'antialiased',
          fontSize: '16px',
          '::placeholder': {
            color: '#aab7c4'
          }
        },
        invalid: {
          color: '#fa755a',
          iconColor: '#fa755a'
        }
      };

      // Create an instance of the card Element
      var card = elements.create('card', {style: style});

      // Add an instance of the card Element into the `card-element` <div>
      card.mount('#card-element');

      // Handle real-time validation errors from the card Element.
      card.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
          displayError.textContent = event.error.message;
        } else {
          displayError.textContent = '';
        }
      });

      // Handle form submission
      var form = document.getElementById('payment-form');
      form.addEventListener('submit', function(event) {
        event.preventDefault();

        stripe.createToken(card).then(function(result) {
          if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
          } else {
            // Send the token to your server
            console.log(result);
            document.getElementById('stripeToken').value=result.token.id;
          }
        });
      });

    </script>
  </body>
</html>