yii2 Multiple model and select2 non-unique id problem - dom

Hi all i'm a noob and i'm tryng to use a multiple model with a select2 in my model i call two time the same table because i write in it two time.
i use a table called "Luoghi" where i write the birthplace and where you live, so i need to use it twice
public function actionView($id)
{
$model = $this->findModel($id);
$ClientiLuoghis = ClientiLuoghi::find()->where(['IDCliente'=>$id])->one();
if (!$ClientiLuoghis) {
throw new NotFoundHttpException("The ClientiLuoghis was not found.");
}
$residenza= Luoghi::find()->where(['ID'=>$ClientiLuoghis->IDLuogo])->one();
if (!$residenza) {
throw new NotFoundHttpException("The residenza was not found.");
}
$lnascita=Luoghi::find()->where(['ID'=>$model->IDLuogoNascita])->one();
if (!$lnascita) {
throw new NotFoundHttpException("The lnascita was not found.");
}
$contatti=contatti::find()->where(['IDCliente'=>$id])->all();
if (!$contatti) {
throw new NotFoundHttpException("The contatti was not found.");
}
$model->Scenario = 'update';
$residenza->Scenario = 'update';
$lnascita->Scenario = 'update';
$contatti->Scenario = 'update';
if($contatti===null) {
throw new CHttpException(404,'The requested page does not exist.');
return $this->render('view', [
'model' => $model,'residenza'=>$residenza,'lnascita'=>$lnascita,'contatti'=>$contatti
]);}
the action works without problems, the trouble is in this
<h3><?= Html::encode('Luogo di Nascita') ?></h3>
<table width="90%">
<tr> <td width="40%"> <?= $form->field($model, 'DataNascita')->widget(DatePicker::classname(), [
'options' => ['placeholder' => 'DataNascita'],
'removeButton' => false,
'pluginOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]); ?></TD><td width="5%"><td width="40%"></tr>
<tr> <td width="40%"> <?=
$form->field($lnascita, 'IDComune')->
widget(Select2::classname(), ['data' => $listComnas,
'id' => 'IDcomune',
'options' => ['placeholder' => 'Seleziona Comune ...', ],
'pluginOptions' => [
'allowClear' => true
],
])->label('Comune');
?></td><td width="5%"><td width="40%">
<?= $form->field($lnascita, 'IDProvincia')->
widget(Select2::classname(), ['data' => $listPRnas,
'id' => 'IDProvincia',
'options' => ['placeholder' => 'Seleziona Provincia ...', ],
'pluginOptions' => [
'allowClear' => true
],
])->label('Provincia');
?>
<h3><?= Html::encode('Luogo di Residenza') ?></h3>
<table width="90%">
<tr> <td width="40%"> <?=
$form->field($residenza, 'IDComune')->
widget(Select2::classname(), ['data' => $listComres,
'options' => ['placeholder' => 'Seleziona Comune ...', ],
'pluginOptions' => [
'allowClear' => true
],
])->label('Comune');
?></td><td width="5%"><td width="40%">
<?= $form->field($residenza, 'IDProvincia')->
widget(Select2::classname(), [
'data' => $listPRres,
'options' => ['placeholder' => 'Seleziona Provincia ...', ],
'pluginOptions' => [
'allowClear' => true
],
])->label('Provincia');
?></td> </tr>
the second IDcomune and IDProvincia select2 are empty and blank and i get this advise
[DOM] Found 2 elements with non-unique id #luoghi-indirizzo input#luoghi-indirizzo.form-control input#luoghi-indirizzo.form-control
Any ideas about how to solve?

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?

Form Collection with choice field

I have a form to modify an entity which has some children entities. I use a form collection to do so. When I edit this entity, the children collection should appear but it doesn't. The children collection is composed of 2 choice fields and 1 integer field. The integer field is well rendered with the right data but choice fields ask to select an option whereas it should show Matiere and Colle of children entities.
In the code, Colle entity is a child of Matiere Entity. I'm using MaterializeCSS as a framework.
Here's my code :
Child Form :
$builder
->add('matiere', EntityType::class, [
'class' => 'PACESColleBundle:Matiere',
'attr' => ['class'=> 'matiere'],
'choice_label' => 'name',
'label' => false,
'required' => false,
'placeholder' => 'Choisissez une matière',
'mapped' => false])
->add('colleEnfant', EntityType::class, [
'class' => 'PACESColleBundle:Colle',
'attr' => ['class' => 'colles'],
'choice_label' => 'nom',
'label' => false,
'group_by' => 'matiere',
'required' => true,
'placeholder' => 'choose.colle'])
->add('ordre', IntegerType::class,[
'attr'=>['class'=>'ordre'],
'required' => true,
'label' => false]);
Parent Form :
$builder->add('nom', TextType::class,['label' => 'Nom de la colle'])
->add('collesEnfants', CollectionType::class,
['label' => false,
'entry_type' => SousColleFormType::class,
'required' => true,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false]);
View :
<table id="tableau" class="creneaux"
data-prototype="{{ form_widget(form.collesEnfants.vars.prototype)|e }}">
<thead>
<tr>
<th>Matière</th>
<th>Colle</th>
<th>Ordre</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
{% for colle in form.collesEnfants %}
<tr>
<td>{{ form_row(colle.matiere) }}</td>
<td>{{ form_row(colle.colleEnfant) }}</td>
<td>{{ form_row(colle.ordre) }}</td>
<td><i class="material-icons">delete</i></td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function() {
$('.matiere').material_select();
$('.colles').material_select()
});
</script>
You could add a query in your entity type and check if the field 'nom' exist in your entity.
$builder->add('colleEnfant', EntityType::class, [
'class' => 'PACESColleBundle:Colle',
'attr' => ['class' => 'colles'],
'choice_label' => 'nom',
'label' => false,
'required' => true,
'placeholder' => 'choose.colle',
'query_builder' => function(ColleRepository $repository) {
$qb = $repository->createQueryBuilder('c');
// the function returns a QueryBuilder object
return $qb->groupBy('c.matiere')->orderBy('c.nom', 'ASC');
}
])
After you need to add an event listener who detect the select modification.
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$matiere = $this->em->getRepository('PACESColleBundle:Matiere')->find($data['matiere']);
$form = $event->getForm();
$form->add('colleEnfant', EntityType::class, [
'class' => 'PACESColleBundle:Colle',
'attr' => ['class' => 'colles'],
'choice_label' => 'nom',
'label' => false,
'required' => true,
'placeholder' => 'choose.colle',
'query_builder' => function(ColleRepository $repository) use ($matiere) {
$qb = $repository->createQueryBuilder('c');
// the function returns a QueryBuilder object
return $qb
->where('c.matiere = :matiere')
->setParameter('matiere', $matiere)
->orderBy('c.nom', 'ASC');
}
]);
});
I hope this going to help you.
I ended up doing it with JQuery.
Script :
$(document).ready(function() {
{% for colleEnfant in collesEnfants %}
$('#paces_colle_colle_ajoutsupercolle_collesEnfants_{{ loop.index0 }}_matiere option[value="{{ colleEnfant.matiere }}"]').prop('selected', true);
$('#paces_colle_colle_ajoutsupercolle_collesEnfants_{{ loop.index0 }}_colleEnfant option[value="{{ colleEnfant.colle }}"]').prop('selected', true);
{% endfor %}
$('.matiere').material_select();
$('.colles').material_select();
}
Controller :
$collesEnfantsForm = [];
foreach ($colle->getCollesEnfants() as $colleEnfant) {
$collesEnfantsForm[] = ['matiere' => $colleEnfant->getMatiere()->getId(), 'colle' => $colleEnfant->getId()];
}
it is because ArrayChoiceList::getValuesForChoices() does comparison for objects by reference. As result if you have not same instance of object in data and in list of choices that it won't be selected. Solution is to use "choice_value" options for ChoiceType field. eg.
$builder->add('type', ChoiceType::class, [
'choices' => FeeType::getTypes(),
'choice_label' => 'name',
'required' => true,
'choice_value' => static function (?FeeType $feeType) {
return $feeType ? $feeType->getId() : '';
}
])

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

$this->getRequest()->getPost() return empty array in magento back end form submission

I am creating a magento custom admin module and a form. I want update this form but not updating. In Controller, under SaveAction() I print $this->getRequest()->getPost() and get empty array. please help me. Below code for form declination..
protected function _prepareForm() {
$form = new Varien_Data_Form(array(
'id' => 'edit_form1',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
And Create a from filed set like
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('qbanner_form', array('legend' => Mage::helper('qbanner')->__('Art information')));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('catalog')->__('Product'),
'required' => false,
'name' => 'name',
));
$fieldset->addField('artist_name', 'text', array(
'label' => Mage::helper('catalog')->__('Artist Name'),
// 'name' => 'artist_name',
'value' => Mage::helper('catalog')->__('Art Name value'),
));
$fieldset->addField('bca_status', 'select', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'bca_status',
'values' =>$this->_getAttributeOptions('bca_status'),
));
$fieldset->addField('reason', 'editor', array(
'name' => 'reason',
'label' => Mage::helper('catalog')->__('Reason'),
'title' => Mage::helper('catalog')->__('Reason'),
'style' => 'width:440px; height:300px;',
'wysiwyg' => true,
'required' => false,
));
$fieldset->addField('thumbnail', 'text', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'thumbnail',
//'values' =>$this->_getAttributeOptions('thumbnail'),
//'renderer' => 'Qaz_Qbanner_Block_Adminhtml_Qbanner_Grid_Renderer_Image'
));
if (Mage::getSingleton('adminhtml/session')->getQbannerData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getQbannerData());
Mage::getSingleton('adminhtml/session')->setQbannerData(null);
} elseif (Mage::registry('qbanner_data')) {
$form->setValues(Mage::registry('qbanner_data')->getData());
}
return parent::_prepareForm();
}
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
Here my
SaveAction()
public function saveAction() {
echo print_r( $this->getRequest()->getPost());
}
I have tied verious post. Any ideas?
Common error for all. You just need to add form key to your form.
Just add this line below your form declaration.
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Like this
<form action="<?php echo Mage::helper("adminhtml")->getUrl("demo/adminhtml_demo/demo");?>" method="post" id="custom-payment-form" enctype="multipart/form-data">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Add this. Now you can get parameters by $this->getRequest()->getPost().
you can get variable of post and get method in magento with $this->getRequest()->getParams(); getParams() method But if you want to get exactly some variable data then use getParam('id');
/magento/catalog/product/view/id/406/category/14
$this->getRequest()->getParam('id') // 406
$this->getRequest()->getParams(); //get all get and post variables