Get gravity forms input labels instead of value - woocommerce

On a WordPress > Woocommerce cart page, I'm using product variables. Instead of the values of the variations, I would like to display the labels.
This are the values:
["_gravity_form_lead"]=>
array(9) {
[3]=>
string(1) "6"
[2]=>
string(1) "6"
[5]=>
string(1) "1"
[6]=>
string(4) "1.25"
[7]=>
string(1) "0"
[8]=>
string(4) "2.85"
["1.1"]=>
string(11) "Total Price"
["1.2"]=>
string(6) "$10.24"
["1.3"]=>
string(1) "1"
}
But for example instead of [5]=>string(1) "1" which is 1, I should have the label of the variation called "Single Sided".
Is there any function that can help me list each every product variation separated and not in group, so I would have total control over them what kind of details to list regarding a variation?

$form_id = RGFormsModel::get_form_id('Form name'); // replace Form name with your form name
$form = GFFormsModel::get_form_meta($form_id);
$field = GFFormsModel::get_field($form, ##); // ## Is the id, so 5 or "1.3"
if(is_array(rgar($field, "inputs"))){ // For the "1.1" etc ID's
foreach($field["inputs"] as $input){
if ( $input['id'] == "##" ) { // ## Is the id, so "1.1", "1.2" etc..
$label = $input['label'];
}
}
} else {
$label = GFFormsModel::get_label($field);
}
In case of the ID's "1.1", "1.2", "1.3", which are grouped ID's, the get_label will return the group name, like when you have a Name and a First name, Last Name. it will return Name. The check for the is_array will give you label names like "First name" for example.
Code wise this should be improved, like looping through the fields you have and doing the above code, but I'm assuming you would know how to code this,

Based on the above answer, I figured out what I needed. Hope that will help also others. Thanks a lot for Peter van der Does!
// get form fields individually
echo '<dl class="variation">';
foreach ($woocommerce->cart->cart_contents as $cart_key => $cart_item_array) {
$form = GFFormsModel::get_form_meta($cart_item_array['_gravity_form_data']['id']);
// height
$height = GFFormsModel::get_field($form, '3');
foreach($height['choices'] as $choice) {
if($choice['value'] == $cart_item_array['_gravity_form_lead']['3']) {
echo '<dt>Height:</dt> <dd>'.$choice['text'].'</dd>';
}
}
// width
$width = GFFormsModel::get_field($form, '2');
foreach($width['choices'] as $choice) {
if($choice['value'] == $cart_item_array['_gravity_form_lead']['2']) {
echo '<dt>Height:</dt> <dd>'.$choice['text'].'</dd>';
}
}
// printing
$printing = GFFormsModel::get_field($form, '5');
foreach($printing['choices'] as $choice) {
if($choice['value'] == $cart_item_array['_gravity_form_lead']['5']) {
echo '<dt>Printing:</dt> <dd>'.$choice['text'].'</dd>';
}
}
// lamination
$lamination = GFFormsModel::get_field($form, '6');
foreach($lamination['choices'] as $choice) {
if($choice['value'] == $cart_item_array['_gravity_form_lead']['6']) {
echo '<dt>Lamination:</dt> <dd>'.$choice['text'].'</dd>';
}
}
// quantity
$quantity = GFFormsModel::get_field($form, '8');
foreach($quantity['choices'] as $choice) {
if($choice['value'] == $cart_item_array['_gravity_form_lead']['8']) {
echo '<dt>Quantity:</dt> <dd>'.$choice['text'].'</dd>';
}
}
}
echo '</dl>';

Related

How do I modify wpDataTables cell values using filters?

In wpDataTables, I would like to modify (i.e. conditionally format) each cell value in a specific column for a specific table programmatically using PHP. How would I accomplish this?
First, install the Code Snippets plugin. Then create a new snippet set to "Run Snippet Everywhere" (required for JSON filtering) using the code below. It will filter both HTML and JSON. For more information, refer to wpDataTables - Filters.
function custom_wpdatatables_filter_initial_table_construct($tbl) {
// Edit below.
$table_name_to_modify = 'My Table Name';
$table_column_to_modify = 'my_table_column';
$cell_modification_function = function($value) {
return 'Modified: ' . $value;
};
// Check table name.
if ($tbl->getName() !== $table_name_to_modify) {
return $tbl;
}
$rows = $tbl->getDataRows();
foreach ($rows as &$row) {
if (array_key_exists($table_column_to_modify, $row)) {
$row['intermentobituary'] = $cell_modification_function($row['intermentobituary']);
}
}
$tbl->setDataRows($rows);
return $tbl;
}
add_filter('wpdatatables_filter_initial_table_construct', 'custom_wpdatatables_filter_initial_table_construct', 10, 1);
function custom_wpdatatables_filter_server_side_data($json, $tableId, $get) {
// Edit below.
$table_name_to_modify = 'My Table Name';
$table_column_to_modify = 'my_table_column';
$cell_modification_function = function($value) {
return 'Modified: ' . $value;
};
// Check table name.
$tableData = WDTConfigController::loadTableFromDB($tableId);
if (empty($tableData->content)) {
return $json;
} else if ($tableData->title !== $table_name_to_modify) {
return $json;
}
// Get columns.
$columns = [];
foreach ($tableData->columns as $column) {
// wdt_ID will be first column.
$columns[] = $column->orig_header;
}
// Modify column values.
$json = json_decode($json, true);
$rows = $json['data'];
foreach ($rows as $row_key => $row_value) {
foreach ($row_value as $row_attr_key => $row_attr_value) {
if ( ! empty($columns[$row_attr_key]) && $columns[$row_attr_key] === $table_column_to_modify) {
$rows[$row_key][$row_attr_key] = $cell_modification_function($row_attr_value);
}
}
}
$json['data'] = $rows;
return json_encode($json);
}
add_filter('wpdatatables_filter_server_side_data', 'custom_wpdatatables_filter_server_side_data', 10, 3);

Contact Form 7 (CF7) Field required if other field filled

I have a CF7-Form that asks for a name and date of birth.
The name is not a required field, but if a name is entered, the birthday is required in any case.
Therefore, the date of birth is not included as required by default.
CF7 Simplified code:
<div class="cf7-conditional-wrapper">
<label>Name [text your-name class:field-a]</label>
<label>Birthday<span class="asterisk-placeholder"></span> [date your-date class:field-b-required-if-a-set]</label>
</div>
In the first step I work on the fact that the field should also be perceived as a required field by CF7.
let cf7_conditional_wrappers = document.getElementsByClassName("cf7-conditional-wrapper");
for (let cf7_conditional_wrapper of cf7_conditional_wrappers) {
let field_a = cf7_conditional_wrapper.getElementsByClassName("field-a")[0],
field_b = cf7_conditional_wrapper.getElementsByClassName("field-b-required-if-a-set")[0],
asterisk_placeholder = cf7_conditional_wrapper.getElementsByClassName("asterisk-placeholder")[0];
if (field_a && field_b && asterisk_placeholder) {
checkRequiredFields(field_a, field_b, asterisk_placeholder);
}
}
function checkRequiredFields(field_a, field_b, asterisk_placeholder) {
let timeout = null;
// Listen for keystroke events
field_a.addEventListener('keyup', function (e) {
clearTimeout(timeout);
timeout = setTimeout(function () {
//console.log('Input Value:', field_a.value);
//console.log('Input Value Length:', field_a.value.length);
if (field_a.value.length > 0) {
// Set Required
field_b.classList.add('wpcf7-validates-as-required');
//field_b.classList.add('wpcf7-not-valid');
field_b.setAttribute("aria-required", "true");
//field_b.setAttribute("aria-invalid", "false");
//field_b.setAttribute("required", "");
//field_b.required = true;
asterisk_placeholder.textContent = "*";
} else {
field_b.classList.remove('wpcf7-validates-as-required');
//field_b.classList.remove('wpcf7-not-valid');
field_b.removeAttribute("aria-required");
//field_b.setAttribute("aria-invalid", "false");
//field_b.removeAttribute("required");
//field_b.required = false;
asterisk_placeholder.textContent = "";
}
}, 1000);
});
}
Everything appears visually to be correct, but the new required field is not checked when the form is submitted.
Does anyone have any tips that I haven't considered?
For safety, I would also solve the same query on the server side via PHP and have looked at the following approach. However, the entry from 2015 was unsuccessful in the first tests, although the code is still similar to that of the plugin's database today.
add_filter( 'wpcf7_validate_date', 'custom_date_confirmation_validation_filter', 20, 2 );
function custom_date_confirmation_validation_filter( $result, $tag ) {
if ( 'birth-date' == $tag->name ) {
$your_birth_date = isset( $_POST['birth-date'] ) ? trim( $_POST['birth-date'] ) : '';
if ( $your_birth_date != '' ) {
$result->invalidate( $tag, "Test to override Required Message" );
}
}
return $result;
}
Example in manual from 2015: https://contactform7.com/2015/03/28/custom-validation/
add_filter( 'wpcf7_validate_date', 'custom_date_confirmation_validation_filter', 20, 2 );
function custom_date_confirmation_validation_filter( $result, $tag ) {
$name = isset( $_POST['name'] ) ? trim( $_POST['name'] ) : '';
if ( 'birth-date' == $tag->name ) {
$your_birth_date = isset( $_POST['birth-date'] ) ? trim( $_POST['birth-date'] ) : '';
if ( trim($name) != '' && trim($your_birth_date) == '' ) {
$result->invalidate( $tag, "Please enter date of birth" );
}
}
return $result;
}
Check if name is not empty and birth date is empty then show warning message.

wordpress wp_mail throws error: could not instantiate mail function

I have two forms in my website. Both were working fine. but suddenly now they are not working. Emails are not going from both the forms.
// This function gets called when user clicks on submit button
<script type="text/javascript">
var $ = jQuery;
function sendMessage(){
var name = $('[name="name"]').val();
var email = $('[name="email"]').val();
var phone = $('[name="phone"]').val();
var message = $('[name="message"]').val();
var filter = /^[7-9][0-9]{9}$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name == '')
{
$('.name-error').show();
}
else
{
$('.name-error').hide();
}
if(email == '')
{
$('.email-error').show();
}
else
{
$('.email-error').hide();
}
if(phone == '')
{
$('.phone-error').show();
}
else
{
$('.phone-error').hide();
}
if(message == '')
{
$('.message-error').show();
}
else
{
$('.message-error').hide();
}
if(name != '' && email != '' && phone != '' && message != ''){
if(emailReg.test(email)){
if(filter.test(phone)){
var data = {
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
action: 'send_mails',
formdata: $("#contact").serialize()
};
var myRequest = jQuery.post(data.url, data, function(response){
console.log(response)
});
myRequest.done(function(){
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
});
$("#contact").trigger("reset");
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
}
else
{
alert("Provide valid mobile number");
}
}
else
{
alert("Provide valid Email Id");
}
}
else
{
// alert("Kindly enter all the details");
return false;
}
}
</script>
This is function from functions.php file.
function send_mails()
{
$formData = $_POST['formdata'];
$data = array();
parse_str($formData, $data);
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$message = $data['message'];
$msg = "A new enquiry has been posted on the website\n";
$msg.= "Name: ".$name."\n";
$msg.= "Email: ".$email."\n";
$msg.= "Phone: ".$phone."\n";
$msg.= "Message: ".$message."\n";
$headers = array('Content-Type: text/html; charset=UTF-8');
//echo $msg;
$admin_email = get_option( 'admin_email' );
// print_r($admin_email);
$res = wp_mail('email',"Enquiry",$msg,$headers);
if($res)
{
echo "Mail has been sent";
}
else
{
echo "Could not send mail";
debug_wpmail($res);
}
die();
}
add_action('wp_ajax_send_mails', 'send_mails');
add_action('wp_ajax_nopriv_send_mails', 'send_mails');
debug_wpmail returns the error "Could not instantiate mail function". I did not find anything on google.
if ( ! function_exists('debug_wpmail') ) :
function debug_wpmail( $result = false ) {
if ( $result )
return;
global $ts_mail_errors, $phpmailer;
if ( ! isset($ts_mail_errors) )
$ts_mail_errors = array();
if ( isset($phpmailer) )
$ts_mail_errors[] = $phpmailer->ErrorInfo;
print_r('<pre>');
print_r($ts_mail_errors);
print_r('</pre>');
}
endif;
Can you modify this part :
From
$res = wp_mail('email',"Enquiry",$msg,$headers);
To
$res = wp_mail($admin_email,'Enquiry',$msg,$headers);
This happens due to your site haven't been configured with email service provider like Google/SendGrid or SMTP Or It just goes removed. Example configuration can be found below:

How to pass an element in Crawler each function?

I parse my xml with Symfony's Crawler and cannot get how can I pass (other words continue) an element and not to include it into final array?
For example:
$node->filterXPath('//ExampleNode')->each(function(Crawler $child, $i) {
if (! count($child->filterXPath('//ChildNode'))) {
continue;
}
return $child->filterXPath('//ChildNode')->text();
});
You can use the Symfony\Component\DomCrawler\Crawler::reduce(Closure)
$crawler->reduce(function($result, $item) {
$childNodes = $item->filterXPath('//ChildNode');
if ($childNodes->count()) {
$result[] = $item;
}
});

ReplyMarkup in php telegram bot

I have problem with my telegram bot.I want to make Keybaord for my bot. When I run my telegram api url from my browser it works:
https://api.telegram.org/mybottoken/sendmessage?chat_id=93119306&text=something&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
but
When I want run to this url($sendto Variable) in my php file this not work.
my php code is:
<?php
define('BOT_TOKEN', '183690241:AAHgluc7D9g0DF_InurfBj2YdBgPE7fmymo');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$array = array();
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$chatText = $update["message"]["text"];
// compose reply
$reply = sendMessage();
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
file_get_contents($sendto);
function sendMessage(){
global $chatID;
global $chatText;
if ($chatText =="/start") {
$message = "Salam - Roboate Megat Hastam";
}
elseif ($chatText =="Khoobi?") {
$message = "Merc - Shomaa khobi?";
}
elseif ($chatText =="Chand salete?") {
$message = "Be Tu Che!";
}
else
{
$message = "No Command";
}
return rawurlencode($message);
}
?>
please help where i made mistake.
thanks all guys.
Try this code:
var_dump($keyboard = json_encode($keyboard = [
'keyboard' => [
['Yes'],['No'],['Maybe'],
['1'],['2'],['3'],
] ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]),true);
function sendKeyboard($chat_id, $keyboard) {
$text = "Merc - Shomaa khobi?";
file_get_contents(API_URL ."sendMessage?chat_id=".$chat_id."&reply_markup=".$keyboard."&text=".urlencode($text));
}
if($message == "/start"){
sendKeyboard($chat_id, $keyboard);
}

Resources