fuction() not working in Detailview yii2 - yii2-advanced-app

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)";
}
}

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

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

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?

Simple Command Controller with TYPO3

I want to set up a simple CommandController but I always get a error Message in the backend.
ext_emconf.php
<?php
$EM_CONF[$_EXTKEY] = [
'title' => 'mytask',
'description' => '',
'category' => 'plugin',
'author' => '',
'author_email' => '',
'state' => 'alpha',
'internal' => '',
'uploadfolder' => '0',
'createDirs' => '',
'clearCacheOnLoad' => 0,
'version' => '1.0.0',
'constraints' => [
'depends' => [
'typo3' => '7.6.0-7.6.99',
],
'conflicts' => [],
'suggests' => [],
],
];
ext_localconf.php
<?php
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers']
[$_EXTKEY] = \TYPO3\CMS\mytask\Command\SimpleCommandController::class;
?>
My command class in /Classes/Command/SimpleCommandController.php
<?php
namespace TYPO3\Mytask\Command;
use \TYPO3\CMS\Extbase\Mvc\Controller\CommandController;
class SimpleCommandController extends CommandController {
public function simpleCommand(){
error_log("Hallo");
}
}
?>
I'm able to find the extension in the backend but when I enable it I get a error message and can't use the backend anymore.
Oops, an error occurred!
syntax error, unexpected '$GLOBALS' (T_VARIABLE)
The extension has only these 3 files.
Just try to increase the array without an extension key:
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][] = \TYPO3\CMS\mytask\Command\SimpleCommandController::class;

Radio button: input was not found in the haystack?

Whenever I submit the form I get this message:
The input was not found in the haystack.
This is for the shipping-method element (radio button). Can't figure out what it means, the POST data for that element is not null.
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
// Some other basic filters
$inputFilter->add(array(
'name' => 'shipping-method',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'max' => 20,
),
),
array(
'name' => 'Db\RecordExists',
'options' => array(
'table' => 'shipping',
'field' => 'shipping_method',
'adapter' => $this->dbAdapter
)
),
),
));
$inputFilter->get('shipping-address-2')->setRequired(false);
$inputFilter->get('shipping-address-3')->setRequired(false);
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
I only keep finding solutions for <select>.
Here's the sample POST data:
object(Zend\Stdlib\Parameters)#143 (1) {
["storage":"ArrayObject":private] => array(9) {
["shipping-name"] => string(4) "TEST"
["shipping-address-1"] => string(4) "test"
["shipping-address-2"] => string(0) ""
["shipping-address-3"] => string(0) ""
["shipping-city"] => string(4) "TEST"
["shipping-state"] => string(4) "TEST"
["shipping-country"] => string(4) "TEST"
["shipping-method"] => string(6) "Ground"
["submit-cart-shipping"] => string(0) ""
}
}
UPDATE:
form.phtml
<div class="form-group">
<?= $this->formRow($form->get('shipping-method')); ?>
<?= $this->formRadio($form->get('shipping-method')
->setValueOptions(array(
'Ground' => 'Ground',
'Expedited' => 'Expedited'))
->setDisableInArrayValidator(true)); ?>
</div>
ShippingForm.php
$this->add(array(
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Shipping Method',
'label_attributes' => array(
'class' => 'lbl-shipping-method'
),
)
));
The problem lies with when you use the setValueOptions() and the setDisableInArrayValidator(). You should do this earlier within your code as it is never set before validating your form and so the inputfilter still contain the defaults as the InArray validator. As after validation, which checks the inputfilter, you set different options for the shipping_methods.
You should move the setValueOptions() and the setDisableInArrayValidator() before the $form->isValid(). Either by setting the right options within the form itsself or doing this in the controller. Best way is to keep all of the options in one place and doing it inside the form class.
$this->add([
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => [
'value_options' => [
'Ground' => 'Ground',
'Expedited' => 'Expedited'
],
'disable_inarray_validator' => true,
'label' => 'Shipping Method',
'label_attributes' => [
'class' => 'lbl-shipping-method',
],
],
]);
Another small detail you might want to change is setting the value options. They are now hardcoded but your inputfilter is checking against database records whether they exist or not. Populate the value options with the database records. If the code still contains old methods but the database has a few new ones, they are not in sync.
class ShippingForm extends Form
{
private $dbAdapter;
public function __construct(AdapterInterface $dbAdapter, $name = 'shipping-form', $options = [])
{
parent::__construct($name, $options)
// inject the databaseAdapter into your form
$this->dbAdapter = $dbAdapter;
}
public function init()
{
// adding form elements to the form
// we use the init method to add form elements as from this point
// we also have access to custom form elements which the constructor doesn't
$this->add([
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => [
'value_options' => $this->getDbValueOptions(),
'disable_inarray_validator' => true,
'label' => 'Shipping Method',
'label_attributes' => [
'class' => 'lbl-shipping-method',
],
],
]);
}
private function getDbValueOptions()
{
$statement = $this->dbAdapter->query('SELECT shipping_method FROM shipping');
$rows = $statement->execute();
$valueOptions = [];
foreach ($rows as $row) {
$valueOptions[$row['shipping_method']] = $row['shipping_method'];
}
return $valueOptions;
}
}
Just had this happen yesterday.
The select and multi select ZF2+ elements have a built in in_array validator.
Remember filters occur before validators.
You may be doing too much here -- it is very rare to need to filter or add validators ot select and multi select form elements in ZF2 forms. The built in element validator is robust, ZF does a lot of work for us.
Try removing both filter and validator for the element, such as:
$inputFilter->add(array(
'name' => 'shipping-method',
'required' => true,
));
There is another edge case that I have seen: changing the select element's valueOptions somewhere in the controller (or view) resulting in different valueOptions used in view vs form validation (in our case it was replacing the element with a new one before validation).
I think your problem lies in the fact you are adding your value options after the InArray validator has been set, hence the validator has no haystack.
Try this
$this->add(array(
'name' => 'shipping-method',
'type' => 'Zend\Form\Element\Radio',
'options' => array(
'label' => 'Shipping Method',
'label_attributes' => array(
'class' => 'lbl-shipping-method'
),
'value_options' => array(
'Ground' => 'Ground',
'Expedited' => 'Expedited'
),
'disable_inarray_validator' => TRUE,
)
));
and remove setValueOptions and setDisableInArrayValidator from your view.
Hope this works.

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...