Add Prefix in text field

When you have to prefix any hard coded value in a text field, like for example in telephone field you have to prefix the country code and dont want the user to remove it, then in that case assign the prefix code in the text field and add the below javascript code code

jQuery("input[name='job-code']").keydown(function(e) {
    var oldvalue = jQuery(this).val();
    var field = this;
    setTimeout(function() {
        if (field.value.indexOf('JPC-') !== 0) {
            jQuery(field).val(oldvalue);
        }
    }, 1);
});

Demo: https://codepen.io/phpweblamp/pen/yLwPqjJ

Detect Change in form fields

<script type=”text/javascript”>
var formChanged = false;
jQuery(window).load(function() { // This is triggered when the entiire page is loaded fully
// form id and all the possible filed type in that form, You can also target by field type, name, class or id
jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).each(function (i)
{
// console.log(‘a’);
jQuery(this).data(‘initial_value’, jQuery(this).val());
});

jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).keyup(function()
{
if (jQuery(this).val() != jQuery(this).data(‘initial_value’)) {
// console.log(‘1’);
handleFormChanged(‘saveDriverInfoBtn’);
}
});
jQuery(‘#FrmIdToTarget input[type=text], #FrmIdToTarget select.form-control’).bind(‘change paste’, function()
{
// console.log(‘b’);
handleFormChanged(‘saveDriverInfoBtn’);
});

jQuery(document.body).on(“click”, “#submitFormButtonId, button.cancelBtnDrvbtn”, function () {
if(formChanged === true){
return confirmNavigation();
}

});

});

function handleFormChanged(formSaveBtnId) {
// alert(‘formSaveBtnId=’+formSaveBtnId);
jQuery(‘#’+formSaveBtnId).removeAttr(‘disabled’);
formChanged = true;
}

function confirmNavigation() {
if (formChanged) {
return confirm(‘You have changes to save, Please save before moving to next tab? Otherwise your changes will be lost!’);
} else {
return true;
}
}
</script>

How to disable specific wordpress plugins from automatic upgrade

Sometime there is need to use some plugins in an application and you have the need to customize it UI or functionality to meet your business requirements.

You install the plugins and make the necessary changes to meet the configuration.

Few week later, you discover that your plugins has lost it custom formatting and the custom workflow due to recent upgrade of the plugins version.
Huhh, now what to do.

Option 1: You may look into your past backupfile to restore the plugins from your back up folder to restore the customized codes. This could be risky or not feasible. For example you may not be having the backup of the plugin , secondly you might get it but may be confused on which version you have to restore, because you had made many backup folder.

Option 2: The recommended way is to disable you customized plugins to get auto upgrade. What you need to do is put this below code in your theme functions.php file.

function disableSpecificPlugins( $value ) {
if( isset( $value->response[‘plugin-folder-name/plugin-name.php’] ) ) {
unset( $value->response[‘plugin-folder-name/plugin-name.php’] );
}
return $value;
}
add_filter( ‘site_transient_update_plugins’, ‘disableSpecificPlugins’ );

Here:

“plugin-folder-name” => plugin folder name

“plugin-name.php” => plugin main file. In most cases , the file name is same as plugin folder name. But it can also be index.hp

Drupal 8 how to get value of the webform submission in webform confirmation twig file

Put the below code in youractivetheme.theme file

/**
* Implements hook_preprocess_HOOK().
*/

function [theme]_preprocess_webform_confirmation(&$vars) {
if ($vars['webform']->id() == 'put your webform id') {
// Set your custom message here
$markup = t('Thank you for your feedback.');
$vars['message']['#markup'] = $markup;
}
}

/// How to customise the message based on the submitted value

/**
* Implements hook_preprocess_HOOK().
*/

function [theme]_preprocess_webform_confirmation(&$vars)
{
if ($vars['webform']->id() == 'put your webform id')
{
// Get the submitted form value using the below command
$submittedFormValues = $vars['webform_submission']->getRawData();
if($submittedFormValues['field_name'] == 'some condition or value'){
$markup = t('display message 1');
}
else
{
$markup = t('display message 2');
}
// Set your custom message here
$vars['message']['#markup'] = $markup;
}
}

How to search string in all files in a folder and sub folder recursivelly

How to use “grep” command in linux or macos to find text inside all files in a folder and including subdirectories

Command for the same is
grep -rl "string to search" /absolute-path/to/folder/

-r (or –recursive) option is used to traverse also all sub-directories of /path
-l (or –files-with-matches) option is used to only print filenames of matching files
-i ( for ignore case sensitive)

If you’re looking for lines matching in files, then use the below command

grep -Hrn "string to search" /absolute-path/to/folder/

-H causes the filename to be printed (implied when multiple files are searched)
-r does a recursive search
-n causes the line number to be printed
/absolute-path/to/folder/ can be . (dot) to search in the current directory

php session handler using mysql on multiple server setup or load balancer setup

Many a time you have to host your website on multiple server such as load balancer to server high traffic website. It is obvious that if i have a load balancer or multiple servers in use, the user’s session is coming from 1 server so if the user is pushed to say server 2 or server 3 then does that mean the user’s session will expire or how to make it work as normal?

I have multi-session checks, so if a user logs-in from a different location it will auto sign them out like we see on bank websites. And this will affect the user journey and create issue to the users? Is there anything I need to do at the database level?

Yes you can do it by using custom session management using MySql or any other database.

Option 1: You can use the common recommended approach suggested by many tech gigs as here https://www.php.net/manual/en/function.session-set-save-handler.php

But sometime, the server configuration doesn’t allow to overwrite the server default session handler, Hence you need to go with some different approach.

Option 2: The way i found the solution.

I created a session handler class using mysql database, create method to start, write, read, unset and destroy the session variable.

Below is the example usage of the same.

Usage Example Just include this file at the top, where you want to manage the session using session data

require_once ‘handleSession.php’; // Make sure to set the Mysql Database credential appropiately

To set session data in DB

Case 1: Set a single session data, pass the key and value in array $cstmSessionHandler->cstm_sess_write(array(‘developer1’=>’1vinod’));

Case 2: To set two dimensional session data, pass the key and value in array as below $newData[‘aaa’][‘ffff’] = ‘1111’; $newData[‘aaa’][‘bbb’] = ‘222’; $cstmSessionHandler->cstm_sess_write($newData);

To read session data

Case 1: To read only a single session variable Pass the session key. $sessionValuesArr = $cstmSessionHandler->cstm_sess_read(‘aaa’);

Case 2: To read all the session which are active. Dont pass any argument $sessionValuesArr = $cstmSessionHandler->cstm_sess_read();

To unset specific session variable $cstmSessionHandler->cstm_sess_unset(‘aaa’);

To destroy all the session variable $cstmSessionHandler->cstm_sess_destroy();

You can download the source code and example from gitlab

https://gitlab.com/vinodkram/php-session-handler-using-mysql-on-load-balancer-setup

WordPress permalink pagination not working

Say for example i have created a custom post type. I have implemented pagination for the same.

When i call this url

http://localhost.dm/news/multi-media-gallery/page/2/, it show page not found.

But if i try with

http://localhost.dm/news/multi-media-gallery?page=2,  it work.

Now to make the pagination work with permalink you need to add the following rewrite rule in your theme functions.php

add_action(‘init’, function ()
{
add_rewrite_rule(‘(.?.+?)/page/?([0-9]{1,})/?$’, ‘index.php?pagename=$matches[1]&paged=$matches[2]’, ‘top’); flush_rewrite_rules();
}, 1000);

Jquery set input value and trigger on blur event

I want to trigger an event every time i click on select on any element by id

First i will try to set the input value by the following code

pickedvalue = jQuery(‘#someElementId’).val();

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)); // use parseInt if the input type is “number” else not required.

After setting the new value to the other element i wanted to fire “on blur” event so to achieve the same use the below code.

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)).trigger(“change”).blur();

 

–Happy Coding

Add default blank value for select option in contact form 7 wordpress

Normally when you use contact form 7 plugin , for dropdown select option, there is no option to set blank value for the first option to validate the select field.

For example, what we have in wordpress contact form 7

<select name=”your_field_name”>
<option value=””>—</option>
<option value=”yes”>Yes</option>
<option value=”no”>No</option>
</select>

But in actual scenario, i want to display the label for the first option as “–Select Value–” with empty value.
To make the same change, you can use the dropdown code as below
[select* your_field_name_ class:form-select class:required first_as_label “–Select Value–” “Yes” “No”]

In the above code “first_as_label” is important parameter. It instruct the plugin to use the first option as label with default empty value. So the generated output look as below

<select name=”your_field_name”>
<option value=””>–Select Value–</option>
<option value=”yes”>Yes</option>
<option value=”no”>No</option>
</select>

If you have any queries, you can write back to us or comment in the comment section.

How to show or hide yii2 gridview action button conditionally

In Yii2 Gridview normally to display the action button we have the following chunk of code

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
]
];

The output you see as below:

Now you have a scenario, to show the edit button only when the “Zone status” is active. So you have to add the additional line

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => [],
'header'=>'Actions',
'template' => '{view} {update} {delete}',
'visibleButtons'=>[
'delete'=> function($model){
return $model->zone_status!='deleted';
},
'view'=> function($model){
return $model->zone_status!='active';
},
]
],
];

Now let me explain what changes were done to display the view button , when zone_status is active.

So the “visibleButtons” control the display of the action button based on the value returned by

function($model){
return $model->zone_status!='active';
}

If the condition hold true, view button will be displayed else not.

Next Level:

You can take this to next level. i.e. if you want to control the button style and the default url for each action, you can do it as below:

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => [],
'header'=>'Actions',
'buttons' => [
'view' => function ($url,$model,$key) {
return Html::a('<button>Details</button>', Url::home()."zone/view?id=".$model->id);
},
'delete' => function ($url,$model,$key) {
if($model->zone_status != 'deleted') {
return Html::a('<button class="bk-custom-btn">Delete</button>', Url::home()."delete?id=".$model->id);
}
},
'update' => function ($url,$model,$key) {
$url = ['zone/update?id='.$model->id];
return Html::a('<button class="bk-edit-btn">Edit</button>',$url);
},
],
'template' => '{view} {update} {delete}',
'visibleButtons'=>[
'delete'=> function($model){
return $model->zone_status!='deleted';
},
'view'=> function($model){
return $model->zone_status=='active';
},
]
],
];

The final output as below: