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

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:

How to create date wise apache error log and access log

By default apache write the access log and error log in the single file. Later it grow in sizes over days and then when you have to debug you find the issue from the apache log, it become difficult to open and read the file. And over a time, the log size bigger so big that, many of the file editor fail to load the file.

Default Logformat
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

So apache come with a inbuilt program called rotatelogs.
First you need to check if rotatelogs is present on your server or not.

To check if rotatelogs is present type the below command
> whereis rotatelogs

The output of the command will be as below
rotatelogs: /usr/bin/rotatelogs /usr/share/man/man8/rotatelogs.8.gz

This “/usr/bin/rotatelogs” indicate that rotatelogs program is present

Now to split your errorlog and accesslog by date, you need to comment the default log format
#ErrorLog ${APACHE_LOG_DIR}/error.log
#CustomLog ${APACHE_LOG_DIR}/access.log combined

and write down the below format.

CustomLog “| /usr/bin/rotatelogs -l /var/log/apache2/access.%Y.%m.%d.log 86400” common
ErrorLog “| /usr/bin/rotatelogs -l /var/log/apache2/error.%Y.%m.%d.log 86400”

What this does is…everyday a new error log and access log file will be created like error.2020.04.03.log and access.2020.04.03.log respectively.

To explore more option for the custom logging you can refer the apache project page http://httpd.apache.org/docs/current/programs/rotatelogs.html

export mysql database – mysql dump

When you have access to the command line and you have the export large database, you will not be able to export from phpmyadmin.

Hence mysql provide you handy method to export the database from the command line. Below are various options, you can use while exporting the database.

——databases – This allows you to specify the databases that you want to backup. You can also specify certain tables that you want to backup. If you want to do a full backup of all of the databases, then leave out this option
——add-drop-database – This will insert a DROP DATABASE statement before each CREATE DATABASE statement. This is useful if you need to import the data to an existing MySQL instance where you want to overwrite the existing data. You can also use this to import your backup onto a new MySQL instance, and it will create the databases and tables for you.
——triggers – this will include the triggers for each dumped table
——routines – this will include the stored routines (procedures and functions) from the dumped databases
——events – this will include any events from the dumped databases
——set-gtid-purged=OFF – since I am using replication on this database (it is the master), I like to include this in case I want to create a new slave using the data that I have dumped. This option enables control over global transaction identifiers (GTID) information written to the dump file, by indicating whether to add a SET @@global.gtid_purged statement to the output.
——user – The MySQL user name you want to use
——password – Again, you can add the actual value of the password (ex. ——password=mypassword), but it is less secure than typing in the password manually. This is useful for when you want to put the backup in a script, in cron or in Windows Task Scheduler.
——single-transaction – Since I am using InnoDB tables, I will want to use this option.
——no-create-db – don’t create database
——no-create-info – don’t create table structure
——extended-insert=FALSE => Each row as seperate insert querry

Syntax : mysqldump ——triggers ——routines ——databases databasename ——user=root ——password > database_export_file_name.sql
Example : mysqldump ——no-create-db ——triggers ——extended-insert=FALSE ——routines ——databases mydatabase ——user=root ——password  > mydatabase.sql

Sometime you have to type the absolute path for mysqldump executable path to execute the above command for example.

Example : /var/mysqlFolder/bin/mysqldump ——no-create-db ——triggers ——extended-insert=FALSE ——routines ——databases mydatabase ——user=root ——password  > mydatabase.sql

More option you can explore on Maria DB website