How to pass relationship data to listview in yii2 - php

im trying to print an attribite from another table in yii2 Listview but im not able to get the data i need to print into the listview
$query = Producto::find()->joinWith(['mPrecios']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 6,
],
]);
Data Provider in search model
$searchModel = new ProductoSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$modelCliente=new Cliente;
$cliente = Cliente::getClientes();
$rows = Producto::autocomplete();//Se envia la variable que contiene los productos a la vista
return $this->render('index', array(
'rows'=>$rows,
'model' => $model,
'modelC'=>$modelCliente,
'searchModel' => $searchModel,
'clientes'=>$cliente,
'listDataProvider' => $dataProvider
)
);
Send DtaProvider through Controller
<?php \yii\widgets\Pjax::begin(['id'=>'listaProductos','enablePushState' => true, 'timeout' => 8000000, 'clientOptions' => ['container' => 'pjax-container']]); ?>
<?=
ListView::widget([
'options'=>[
'class'=>'col-lg-12 list-wrapper inline row-eq-height',
],
'dataProvider' => $listDataProvider,
'itemView' => function ($model, $key, $index, $widget) {
$itemContent = $this->render('_tabla_producto',['model' => $model]);
return $itemContent;
},
'itemOptions' => [
'tag' => false,
],
'summary' => '',
'layout' => '{items}{pager}',
'pager' => [
'firstPageLabel' => 'Primera',
'lastPageLabel' => 'Ultima',
'maxButtonCount' => 5,
'options' => [
'class' => ' pagination col-xs-12'
]
],
]);
?>
<?php \yii\widgets\Pjax::end(); ?>
ListView
<?php $IdProducto = $model['Refe'];?>
<div id="producto-<?php echo $IdProducto;?>" class="content inline producto col-lg-4 box-body" >
<div class="row">
<div class="col-lg-6">
<img class='img-responsive' src="<?php echo $model['ImagenProducto']?>"/>
</div>
<div class="row">
<div class="col-lg-6" style="height:200px;">
<?php
if($model['Fraccion'] > 1){
echo "<button id='fraccion-$IdProducto' class='btn btn-danger btn-xs fraccionado' data-toggle='modal' data-target='#modalFraccion'><b>F</b></button>";
}
else{
echo "<button id='fraccion-$IdProducto' class='btn btn-default btn-xs disabled'><b>NF</b></button>";
}
?><br>
<b>Nombre:</b><br><?= $model['DescripcionCorta'] ?><br>
<b>Presentacion:</b><br><?= $model['PresentacionCorta'] ?><br>
<b>Precio:</b> HERE GOES THE OTHER TABLE ATTRIBUTE
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<span class="input-group-btn" >
<button id="menos-<?php echo $IdProducto;?>" type="button" class="btn btn-sm btn-default btn-minuse" min='0' value="0">-</button>
</span>
<input id="input-<?php echo $IdProducto;?>" type="text" value="0" class="form-control text-center" style="height:30px;">
<span class="input-group-btn">
<button id="mas-<?php echo $IdProducto;?>" type="button" class="btn btn-sm btn-default btn-pluss" min='0' value="0">+</button>
</span>
</div>
</div>
<div class="col-lg-6 pull-left">
<button id="anadir-<?php echo $IdProducto;?>" type="button" class="text-center center-block btn btn-sm btn-default btn-add">Añadir</button>
</div>
</div>
</div>

I will assume you have your relation set up correctly in your model, getMPrecios().
If this is a hasOne() you can access the relational data with $model->mPrecios->attributeName and if its a hasMany() you'll have to do a
foreach($model->mPrecios as $mprecios)
{
echo $mprecios->attributeName;
}
This relational values should be accessible regardless of whether you eagerly load them (like you do with a joinWith()) or lazy load them.

Related

yii2 two active form requires second click to submit

I have two activeform in my view and one of them use pjax. And both of them requires second click to submit. I don't know what I am doing wrong. I search this problem in internet, but meet other cases of second click
<?php Pjax::begin(['id' => 'workers', "timeout" => 50000], ["options" => ["timeout" => 5000]]);?>
<?php
echo $this->render('_show', [
"model" => $searchModel,
"filials" => $filials,
"workers" => $workers,
"posts" => $posts,
]);
echo $this->render('_handle_form');
?>
<div class="row js-loader">
<div class="col-lg-12 col-md-12">
<div class="table-responsive">
<?=GridView::widget([
'dataProvider' => $dataProvider,
'emptyText' => 'Нет результатов',
'tableOptions' => ['class' => 'table table-hover table-claim table-claimadm', 'style' => 'font-weight:600;'],
'rowOptions' => ['class'=>'row-without-border row-open'],
'layout' => "{items}{pager}",
'columns' => [
[
...
]
]);?>
</div>
</div>
</div>
<?php Pjax::end();?>
<script>
window.onload = function () {
$(document).on('pjax:send', function (event) {
tbody = $('#' + event.target.id).find(".js-loader");
if (tbody.length != 0) {
tbody_height = tbody.height();
tbody.html('<div class="block-loader" style="width:100%"></div>');
}
});
$('#submit_with_answer').click(function() {
if ($.trim($('#text-claim').val()).length > 0)
{
$('#complaint_feedback').submit();
}
else
{
$('#textarea-group').addClass('has-error');
$('#answer_error').html('Заполните поле «Добавить текст ответа»');
}
});
};
</script>
The "_show" view is:
<?php $form = ActiveForm::begin([
'id' => 'complaints',
'action' => Url::to(['complaints/show']),
'method' => 'GET',
'options' =>
[
'class' => 'form-respons form-claimadm',
'data-pjax' => 1,
],
]);
active fields....
<div class="form-btns col-md-2 col-sm-6 col-xs-12">
<?= Html::submitButton('Применить', ['class' => 'btn btn-primary','style'=>"float:right;"]) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
and _handle_form is:
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
?>
<?php
$form = ActiveForm::begin([
'id' => 'complaint_feedback',
'action' => Url::to(['complaints/handle-complaint']),
'method' => 'POST',
'options' => ['class' => 'form-respons form-claim-feedback','style'=>'display:none;'],
]);
?>
<div id="textarea-group" class="form-group">
<label for="text-claim" class="hidden-xs">Добавить текст ответа</label>
<textarea class="form-control" id="text-claim" rows="3" name="complaint_answer" placeholder="Добавить текст ответа"></textarea>
<div id="answer_error" class="help-block"></div>
<input id="complaint_id" name="complaint_id" type="hidden" value="">
</div>
<div class="clearfix form-btns">
<button type="button" onclick="$('#complaint_feedback').submit();" class="btn btn-link">Обработать без ответа</button>
<button id="submit_with_answer" type="button" class="btn btn-primary">Отправить</button>
</div>
<?php ActiveForm::end(); ?>
<a id="hide_handle_form" style="display: none;" onclick="$('#complaint_feedback').hide(); $('.handle_button').removeClass('disabled'); $(this).hide();$('tr[data-key='+$('#complaint_id').val()+']').removeClass('row-open');" class="btn btn-link btn-show-hide">Свернуть
</a>
if I comment lines with pjax, everything works correctly. How can I fix this trouble?

yii2 upload file inside dynamic form return unrecognized expression

I have my dynamic form using wbraganca widget and kartik file upload inside it. When I open the page, the field was just showing spinner image instead of a textfield and the console display "unrecognized expression: #tcandidateexp-{$i}-prod_per_year_file". The field I want to use as a file upload is "prod_per_year_file". Any help would be appreciate. Thanks.
<?php $form = ActiveForm::begin(['id' => 'dynamic-form', 'options'=>['enctype'=>'multipart/form-data']]); ?>
<div class='row'>
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 5, // the maximum times, an element can be added (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $models_exp[0],
'formId' => 'dynamic-form',
'formFields' => [
'start_year',
'end_year',
'company',
'prod_per_year',
'prod_per_year_file',
'inc_per_year',
'inc_per_year_file'
],
]); ?>
<div class="panel panel-default" style="width:85%">
<div class="panel-heading">
<h4>
<i class="glyphicon glyphicon-envelope"></i> Experiences
<button type="button" class="add-item btn btn-success btn-sm pull-right"><i class="glyphicon glyphicon-plus"></i> Add</button>
</h4>
</div>
<div class="panel-body">
<div class="container-items"><!-- widgetBody -->
<?php foreach ($models_exp as $i => $model_exp): ?>
<div class="item panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Detail</h3>
<div class="pull-right">
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $model_exp->isNewRecord) {
echo Html::activeHiddenInput($model_exp, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6" >
<?=
$form->field($model_exp, "[{$i}]start_year")->textInput();
?>
</div>
<div class="col-sm-2">
<?=
$form->field($model_exp, "[{$i}]end_year")->textInput();
?>
</div>
<div class="col-sm-2">
<?=
$form->field($model_exp, "[{$i}]company")->textInput();
?>
</div>
<div class="col-sm-10">
<?= $form->field($model_exp, "[{$i}]prod_per_year")->textInput() ?>
</div>
<div class="col-sm-10">
<?php
//$form->field($model_exp, "[{$i}]prod_per_year_file")->textInput()
echo $form->field($model_exp, '[{$i}]prod_per_year_file')->widget(FileInput::classname(), [
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false
]
]);
?>
</div>
<div class="col-sm-10">
<?= $form->field($model_exp, "[{$i}]inc_per_year")->textInput() ?>
</div>
<div class="col-sm-10">
<?= $form->field($model_exp, "[{$i}]inc_per_year_file")->textInput() ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div><!-- .panel -->
<?php DynamicFormWidget::end(); ?>
</div>
Try replace the single quotes with double quotes
echo $form->field($model_exp, "[{$i}]prod_per_year_file")->widget(FileInput::classname(), [
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false
]
]);

Dropdown Button Yii2

I want to make a dropdown button and when I tried to make it, the position of dropdown list not in the center.
Here is my code:
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\bootstrap\Dropdown;
/* #var $this yii\web\View */
?>
<div class="site-index">
<div class="jumbotron">
<h1>Selamat Datang!</h1>
<p class="lead-lg-5">
Aplikasi ini ditujukan untuk menampilkan <br>
data-data dan statistik mahasiswa program Pascasarjana Universitas
</p>
<div class="col-md-12 school-options-dropdown text-center">
<div class="dropdown btn-group"> <div class="btn btn-success btn-sm">
Pilih Tahun Periode<b class="caret"></b>
<?php
echo Dropdown::widget([
'items' => [
['label' => 'Periode 2001-2005', 'url' => "index.php?r=site%2Findexumum"],
['label' => 'Periode 2006-2010', 'url' => '#'],
['label' => 'Periode 2011-2015', 'url' => '#'],
],
]);
?>
</div>
</div>
</div>
</div>
</div>
Here is the result:
What may I do to solve that? Thanks in advance

Link to controller action in html

It is possible to create
href="controller action"
with id of model?
I have this code and i want to use html href to actions of controller.
<?php
use yii\helpers\Html;
use yii\helpers\Url;
?>
<div class="news">
<div class="context-menu">
<i class="icon-circle-down"></i>
<ul class="dropdown-menu" aria-labelledby="dropdownProfile">
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
</ul>
</div>
<div class="header-news">
<img src="<?= Url::base(true) ?>/img/ania.jpg" alt="">
<p class="author"><?= $model->getUser($model->urUser_Id); ?></p>
<p class="date"><?= $model->CreatedAt; ?></p>
</div>
<div class="content-news">
<p><?= $model->Text; ?></p>
</div>
<?= $model->getStatus($model->cnNewsContentType_Id); ?> <br>
<?php
if ($model->getId($model->urUser_Id) == Yii::$app->user->identity->Id) {
echo Html::a(Yii::t('app', 'Edytuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']);
echo Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chcesz usuńąć tego newsa?'),
'method' => 'post',
],
]);
}
?>
</div>
There is dropdown list in html where i want to paste link of actions of my controller.
<li>Lorem ipsum</li>
<li>Lorem ipsum</li>
There instead of # i want to use this action edit and delete it is possible?
<li>
<?php echo Html::a(Yii::t('app', 'yourItemLabel'),
Url::to(['/yourController/yourAction',
'id' => $model->id]), ['class' => 'btn btn-primary']) ?>
</li>;
or you can simply assign an url to your href
this sample is for a relative path
echo '<a href="./index.php/myController/myActio/?id=1"
class="btn btn-success btn-block">mylinktext</a>';

Cakephp2.3 Text Area isn't being posted correctly

I am trying to save a description field that has varchar(500) in the database. When I look at the Net Panel in firebug the entire description is being posted (200+ words). However, in cakephp only 75 words are being saved. I set a breakpoint in my controller and looked at this->request->data and it has about 150 characters. Below is my code:
<fieldset>
<legend>Create Log</legend>
<?php echo $this->Form->Create('Log', array('inputDefaults' => array('div' => false, 'label' => false))); ?>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-folder-open"></i></span>
<?php echo $this->Form->input('project_id'); ?>
</div>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="txtName" placeholder="Customer" />
<?php echo $this->Form->Hidden('customer_id'); ?>
<a><span class="add-on"><i class="icon-plus" style="color: green;" onclick="window.open('<?php echo $this->Html->Url(array('controller' => 'customers', 'action' => 'add?popup')); ?>', 'Add Customer', 'height=630, width=430')"></i></span></a>
</div>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-time"></i></span>
<?php echo $this->Form->input('time_spent', array('placeholder' => 'Time spent (hrs)')); ?>
</div>
</div>
<div class="control-group">
<div class="input-prepend">
<span class="add-on"><i class="icon-book"></i></span>
<?php echo $this->Form->textarea('description', array('placeholder' => 'Description', 'class' => 'logTextArea', 'rows' => '7')); ?>
</div>
</div>
<?php echo $this->Form->end(array(
'label' => 'Save Record',
'class' => 'btn btn-primary',
'div' => false
)); ?>
<?php echo $this->Html->script('jquery.autocomplete', array('inline' => false)); ?>
<?php $this->start('script'); ?>
<script type="text/javascript">
$(document).ready(function () {
var options, a;
jQuery(function() {
options = {
serviceUrl: "<?php echo $this->Html->Url(array('controller' => 'logs', 'action' => 'autoComplete.json')); ?>",
minChars: 2,
onSelect: function(suggestion){ $('#LogCustomerId').val(suggestion.data); }
};
a = $('#txtName').autocomplete(options);
});
});
</script>
<?php $this->end(); ?>
Controller:
public function add() {
$this->set('title_for_layout', 'Add log');
// Populate projects DDL
$this->set('projects', $this->Log->Project->find('list', array(
'order' => array('Project.project_name')
)));
if ($this->request->is('post'))
{
$this->Log->create();
if ($this->Log->save($this->request->data))
{
$this->Session->setFlash('Log has succesfully been created', 'default', array('class' => 'alert alert-success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to save log', 'default', array('class' => 'alert alert-error'));
}
}
}
This problem may be caused by a bug in some versions of PHP that truncates $_POST values.
Without re-posting the information, this question contains some additional
information.
PHP $_POST array variables are truncated
Some (possibly) related bugs;
Bug #42824 Post Data truncated

Categories