when selecting an option, show data from the database - Woocommerce custom fields (checkout) - select

I have the following code to generate a select and bring the values inside the options:
add_action('woocommerce_after_order_notes', 'cliente_woocommerce');
function cliente_woocommerce($checkout)
{
global $wpdb;
/// in tab_clientes have id, nome, cpf, cnpj, ie, email, data_since columns
$results = $wpdb->get_results("SELECT * FROM tab_clientes");
$options = ['' => __('Selecione o cliente')];
foreach ($results as $result) {
$options[$result->nome] = $result->razao_social;
}
echo '<div id="cliente_woocommerce"><h2>' . __('Cliente') . '</h2>';
woocommerce_form_field(
'cliente',
[
'type' => 'select',
'class' => ['cliente form-row-wide'],
'label' => __('Campo de Teste (Cliente)'),
'options' => $options,
],
$checkout->get_value('cliente')
);
woocommerce_form_field(
'nome',
[
'type' => 'text',
'class' => ['nome form-row-wide'],
'label' => __('Razão Social'),
'default' => '',
],
$checkout->get_value('nome')
);
woocommerce_form_field(
'cnpj',
[
'type' => 'text',
'class' => ['cnpj form-row-wide'],
'label' => __('CNPJ'),
'default' => '',
],
$checkout->get_value('cnpj')
);
echo '</div>';
}
with the following script:
$(document).ready(function()
{
$('#cliente').change(function() {
$('#nome').val( $( this ).val() );
});
$('#nome').change(function() {
$('#cnpj').val( $( this ).val() );
});
});
When I select the client, the #nome field (razão social - in the table = razao_social) appears with the correct value, but the value repeats within CNPJ field.
what am I doing wrong?

Related

Request timeout - integrate third party library with codeigniter 3

Im working on API integration InPost API Create shippment. I try integrate third party library inpost with codeigniter 3 from GitHub.
https://github.com/imper86/php-inpost-api
I install this library via composer.
View:
<?php echo form_open('inpost_controller/inpost_shippment_post'); ?>
<div class="form-group">
</div>
</div>
<?php echo form_close(); ?><!-- form end -->
Then I call in controller:
require FCPATH . 'vendor/autoload.php';
Full code file Controller:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
require FCPATH . 'vendor/autoload.php';
use Imper86\PhpInpostApi\Enum\ServiceType;
use Imper86\PhpInpostApi\InpostApi;
class Inpost_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
/**
* Create shippment Inpost Post
*/
public function inpost_shippment_post()
{
$token = 'xxxxx';
$organizationId = 'xxxxx';
$isSandbox = true;
$api = new InpostApi($token, $isSandbox);
$response = $api->organizations()->shipments()->post($organizationId, [
'receiver' => [
'name' => 'Marek Kowalczyk',
'company_name' => 'Company name',
'first_name' => 'Jan',
'last_name' => 'Kowalski',
'email' => 'test#inpost.pl',
'phone' => '888888888',
'address' => [
'street' => 'Malborska',
'building_number' => '130',
'city' => 'Kraków',
'post_code' => '30-624',
'country_code' => 'PL',
],
],
'sender' => [
'name' => 'Marek Kowalczyk',
'company_name' => 'Company name',
'first_name' => 'Jan',
'last_name' => 'Kowalski',
'email' => 'test#inpost.pl',
'phone' => '888888888',
],
'parcels' => [
['template' => 'small'],
],
'insurance' => [
'amount' => 25,
'currency' => 'PLN',
],
'cod' => [
'amount' => 12.50,
'currency' => 'PLN',
],
'custom_attributes' => [
'sending_method' => 'parcel_locker',
'target_point' => 'KRA012',
],
'service' => ServiceType::INPOST_LOCKER_STANDARD,
'reference' => 'Test',
'external_customer_id' => '8877xxx',
]);
$shipmentData = json_decode($response->getBody()->__toString(), true);
while ($shipmentData['status'] !== 'confirmed') {
sleep(1);
$response = $api->shipments()->get($shipmentData['id']);
$shipmentData = json_decode($response->getBody()->__toString(), true);
}
$labelResponse = $api->shipments()->label()->get($shipmentData['id'], [
'format' => 'Pdf',
'type' => 'A6',
]);
file_put_contents('/tmp/inpost_label.pdf', $labelResponse->getBody()->__toString());
}
}
When I post form, after 30 sec I get error 500 Internar Error Server Request timout.
And now im not sure how to debug now. I enable error log in CI3 application/logs/ I open this file but I not see any error related to this.
Could be a defect, or missing http2 setup/cfg.
Since the header in https2 protocol has shorter header on packs.
Not sure doe
https://caniuse.com/http2 < short http2 (TLS, HTTPS) overview
https://factoryhr.medium.com/http-2-the-difference-between-http-1-1-benefits-and-how-to-use-it-38094fa0e95b < http2 as protocol overview in 5 min

How can I save dynamically created Gravity Form fields into entries content?

The code below successfully creates a dynamic field and for a Gravity Form, and on submission the dynamic field data is included in the email content sent. However the dynamic field isn't saved in the "entries" data for that form submission, only the fields created manually using the plugin are. Anyone know how to include this data in the entries data saved?
add_filter('gform_pre_render_5', 'populate_wines');
add_filter('gform_pre_validation_5', 'populate_wines');
function populate_wines($form) {
// create dynamic select field
$props = array(
'id' => 51,
'type' => 'select',
'label' => 'Dynamic field label',
'choices' => array(
array(
'text' => '',
'value' => '',
),
array(
'text' => '1',
'value' => '1',
),
array(
'text' => '2',
'value' => '2',
),
array(
'text' => '3',
'value' => '3',
),
)
);
$new_field = GF_Fields::create( $props );
$form['fields'][] = $new_field;
return $form;
}
Edit: Dave's solution below works great for the above function (thanks!!), but adding to the function to include the looped wine list (code below), it doesn't work, any ideas?
function populate_wines($form) {
// options for select lists
$select_choices = array(
array(
'text' => '',
'value' => '',
),
array(
'text' => '1',
'value' => '1',
),
array(
'text' => '2',
'value' => '2',
),
array(
'text' => '3',
'value' => '3',
),
);
// loop through wine list
if( have_rows('wine_options') ):
$wine_count = 50;
while( have_rows('wine_options') ) : the_row();
$wine_ID = get_sub_field('wine_option');
$wine_name = get_the_title($wine_ID);
// create wine select field
$props = array(
'id' => $wine_count,
'type' => 'select',
'label' => $wine_name,
'choices' => $select_choices
);
$new_field = GF_Fields::create( $props );
$form['fields'][] = $new_field;
$wine_count++;
endwhile;
endif;
if ( GFForms::get_page() !== 'form_editor' ) {
return $form;
}
}
You'll need to call the same function on the gform_admin_pre_render filter. My recommendation would be to also add a check to exclude it from being output in the form editor but you may want that. If you don't, it'd look something like this:
if ( GFForms::get_page() !== 'form_editor' ) {
return $form;
}

Magento 2 Get Category list in admin tab/main.php

I have created a custom module.Now I want to get categories in drop down in admin.
The file is on the following path,
app/code/vendor/theme/block/adminhtml/catbanner/edit/tab/Main.php
The html is for dropdown is,
$fieldset->addField(
'banner_category',
'select',
[
'label' => __('Select Category'),
'title' => __('Select Category'),
'name' => 'banner_category',
'required' => true,
'options' => \vendor\module\Block\Adminhtml\Catbanner\Grid::getOptionArray1(),
'disabled' => $isElementDisabled
]
);
I want the options to be populated by the categories.Kindly help how can i do that?
Use below code for fieldset
$fieldset->addField(
'category',
'select',
[
'name' => 'category',
'label' => __('Category'),
'id' => 'category',
'title' => __('Category'),
'values' => \vendor\module\Block\Adminhtml\Catbanner\Grid::getOptionArray1(),
'class' => 'category',
'required' => true,
]);
In your grid block use below code:
public function getOptionArray1()
{
$categoryCollection = $this->_categoryCollectionFactory->create()
->addAttributeToSelect(array('id','name'))
->addAttributeToFilter('is_active','1');
$options = array();
foreach($categoryCollection as $category){
$options[] = array(
'label' => $category->getName(),
'value' => $category->getId()
);
}
return $options;
}
Hope this will work for you...

fuction() not working in Detailview yii2

When i am going to show user details in Detailview than it throws:
htmlspecialchars() expects parameter 1 to be string, object given
Below is my code for Detailview:
view.php
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'userID',
'userEmail:email',
'userName',
'userMobile',
'userBirthDate',
'userGender',
[
'attribute' => 'interestName',
'format' => 'raw',
'label' => 'Interest',
'value' => $model->getUserinterest(),
],
'userStatus',
'userType',
],
]);
?>
function getUserinterest() {
foreach ($model->userinterest as $userinterest) {
$interestNames[] = $userinterest->interestName;
}
return implode("\n", $interestNames);
}
Since version 2.0.11 value can be defined as closure. Upgrade Yii version to developer version 2.0.11+ and it will work.
Follow the final answer as below:
view.php
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'userID',
'userEmail:email',
'userName',
'userMobile',
'userBirthDate',
'userGender',
[
'attribute' => 'interestName',
'format' => 'raw',
'label' => 'Interest',
'value' => $model->getviewinterest(),
],
'userStatus',
'userType',
],
]);
?>
Users.php(Model)
public function getviewinterest()
{
foreach ($this->userinterest as $userinterest)
{
$interestNames[] = $userinterest->interestName;
}
if(!empty($interestNames)){
return implode("<br/>", $interestNames);
}else{
return "(not set)";
}
}

Web::Scraper nested structures & elements only containing spesific data

I have the following code to scrape a form for inputs and get the attributes id and name.
#!/usr/bin/perl
use warnings;
use strict;
use URI;
use Data::Dumper::Simple;
use Web::Scraper;
my $urlToScrape = "http://digitalarkivet.arkivverket.no/finn_kilde";
my $scrap = scraper {
process 'div.listGroup.open > ul.grouped > li.expandable', 'data[]' => scraper {
process 'input', 'id' => '#id', name => '#name';
process 'label', 'label_for' => '#for';
process 'span.listExpander ', 'Text' => 'TEXT';
process 'ul.sublist1', 'sublist[]' => scraper {
process 'input', 'id' => '#id', name => '#name';
process 'label', 'label_for' => '#for';
process 'span', 'label' => 'TEXT';
};
};
};
my $res = $scrap->scrape(URI->new($urlToScrape));
print Dumper($res);
which gives me (shortend $res to fit screen better)
$res = {
'data' => [
{
'label_for' => 'ka0',
'sublist' => [
{
'label' => 'Statlig folketelling',
'label_for' => 'ka0kt0',
'name' => 'kt[]',
'id' => 'ka0kt0'
}
],
'name' => 'ka[]',
'id' => 'ka0>',
'Text' => 'Folketellinger'
},
{
'sublist' => [
{
'label' => 'Manntall',
'name' => 'kt[]',
'label_for' => 'ka1kt0',
'id' => 'ka1kt0'
}
],
'label_for' => 'ka1',
'id' => 'ka1>',
'name' => 'ka[]',
'Text' => 'Manntall'
},
....
{
'label_for' => 'r0',
'sublist' => [
{
'label_for' => 'r0f0',
'id' => 'r0f0',
'name' => 'f[]',
'label' => "01 Østfold"
}
],
'id' => 'r0',
'name' => 'r[]',
'Text' => "Østlandet"
},
{
'Text' => "Sørlandet",
'id' => 'r1',
'sublist' => [
{
'label_for' => 'r1f0',
'name' => 'f[]',
'id' => 'r1f0',
'label' => '09 Aust-Agder'
}
],
'label_for' => 'r1',
'name' => 'r[]'
}
]
};
I' have 2 issues I need to fix. First, I only want to get data for inputs having 'name' = ka[] (at top level).
Second, I only get data for first ul.sublist1 (If you study the page I'm scraping you can see that several "Kildekategori" have subsets of data, which are revealed if expanded/ clicked upon. Putting brackets on Text[] only gets me the sublist textnames, but not their attributes.
I'm thinking I might have to grab data in 2 scrapes instead, since nested values are revealed by id and label_for.
Solved it by scraping three times, foreach "level"
#!/usr/bin/perl
use strict;
use warnings;
use URI;
use Web::Scraper;
use Data::Dumper::Simple;
my %site;
my #res;
my $i;
my $j;
my $label_for;
my #scrape;
$site{'siteID'} = 1;
$site{'url'} = "http://digitalarkivet.arkivverket.no/finn_kilde";
$site{'name'} = "finn_kilde";
open FIL, ">$site{'name'}.csv" or die $!;
my $seperator=";";
$scrape[0] = scraper {
process 'div.listGroup.open > ul.grouped > li.expandable', 'data[]' => scraper {
process 'input',
'id' => '#id',
'value' => '#value',
'type' => '#type',
'name' => '#name';
process 'label', 'label_for' => '#for';
process 'span.listExpander ', 'text' => 'TEXT';
};
};
$scrape[1] = scraper {
process 'ul.sublist1 > li', 'data[]' => scraper {
process 'input',
'id' => '#id',
'value' => '#value',
'type' => '#type',
'name' => '#name';
process 'label', 'label_for' => '#for';
process 'span', 'text' => 'TEXT';
}
};
$scrape[2] = scraper {
process 'ul.sublist2 > li', 'data[]' => scraper {
process 'input',
'id' => '#id',
'value' => '#value',
'type' => '#type',
'name' => '#name';
process 'label', 'label_for' => '#for';
process 'span', 'text' => 'TEXT';
}
};
for $i (0 .. $#scrape){
$res[$i] = $scrape[$i]->scrape(URI->new($site{'url'}));
unless ($i) {
print FIL join($seperator,"label_for","text","name","value","id","type")."\n";
}
for $j (0 .. $#{$res[$i]->{data}}) {
if (defined($res[$i]->{data}[$j]->{label_for})){
$label_for=$res[$i]->{data}[$j]->{label_for};
} else {
$label_for="";
}
if (length($label_for)>0) {
my $name=$res[$i]->{data}[$j]->{name};
my $text=$res[$i]->{data}[$j]->{text};
my $value=$res[$i]->{data}[$j]->{value};
my $id=$res[$i]->{data}[$j]->{id};
my $type=$res[$i]->{data}[$j]->{type};
my #row=($label_for,$text,$name,$value,$id,$type);
print FIL join($seperator,#row);
print FIL "\n";
}
}
sleep(2);
}
close FIL;
print Dumper(\#res);
1;