I have the below cake php form in my view:
<?php $form_id = 'message_form ' + $profile_id ?>
<?php echo $this->Form->create('Post', array('id' => $form_id, 'url' => array('app' => true, 'controller' => 'messages', 'action' => 'new', $profile_id))); ?>
<?php echo $this->Form->input('text', array('type' => 'textarea', 'class' => 'form-control', 'label' => false, 'data-validate' => 'not-empty', 'name' => 'data[Message][content]', 'placeholder' => 'Reply...')); ?>
<?php echo $this->Form->input('hidden', array('type' => 'hidden', 'class' => 'form-control', 'label' => false, 'name' => 'data[Message][parent_id]', 'value' => 1)); ?>
<div class="message-reply-options">
<i class="fa fa-camera"></i>
<i class="fa fa-paperclip"></i>
<i class="fa fa-trash"></i>
<span class="pull-right">
<?php echo $this->Form->submit('Send', array('class' => 'form-control')); ?>
</span>
</div>
<?php echo $this->Form->end(); ?>
This works fine, however I need to be able to change the hidden fields value via javascript depending on something the user does else where on the page.
Below is my current javascript I am using for this, however it does not change the value (but gives no error either).
var newestmessage = response.ChildMessage[response.ChildMessage.length-1];
var parentid = newestmessage.parent_message_id;
document.getElementsByName('data[Message][parent_id]').value = $parentid;
This would have probably been a comment, but since I don't have enough reputation...
I guess you are trying to change/assign the value to hidden field on a particular, action.
I just assume a click event.
Jquery required
$('.classNameOfClickableObjt').clilck(function(){
$('input[name="data[Message][parent_id]"]').val(parentid);
/*Another alternative, you might assign attribute, like
$('input[name="data[Message][parent_id]"]').attr('value', parentid); */
})
You can try jquery and ajax functionally to check the value of hidden input box.
Related
$user
id
name
001
user 1
002
User 2
<ul>
<?php foreach($user as $user( { ?>
<input class="is-selected" type="checkbox" value="<?= $value->user->id ?>" />
<?php } ?>
</ul>
<button type="submit" class="btn is-primary">Send Reminder</button>
I'm using YII2, I'm displaying a list of inactive users. I'm using the checkbox to select the user. I'm going to send an email to the user I tagged.
how can i get id value from that checkbox and send data to controller?
I try to use javascript/jquery but i can't solved yet, i need some help from you guys
The above screenshot and your implementation is like you are talking 2 different things.
You would just be required a Grid View with CheckboxColumn
<?php
use yii\bootstrap\ActiveForm;
use yii\grid\GridView;
use yii\helpers\Html;
$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'id' => 'user_form',
'options' => ['class' => 'lfp-listing']
]);
echo Html::submitButton('Send Reminder', ['class' => 'btn is-primary', 'name' => 'action', 'value' => 'send_reminder']);
echo GridView::widget([
'dataProvider' => $dataprovider,
'columns' => [
'id',
'name',
'email',
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' =>
function ($model) {
return ['value' => $model->id, 'class' => '', 'id' => 'checkbox'];
}
],
]
]);
ActiveForm::end();
Considering your Action is actionIndex()
public function actionIndex()
{
if (isset($_REQUEST['action']) && isset($_REQUEST['selection']) && 'send_reminder' == $_REQUEST['action'] ) {
foreach ($_REQUEST['selection'] as $userIds) {
//write down the email code here....
}
}
I did a simple gridview table with filters on yii2, seems to be working great, but I noticed the javascript functions doesn't work after I apply any filter on the gridview table, i think its refreshing the whole page instead only refresh the table.
I did the $.pjax.reload method but it didn't work, this is how i applied the pjax reload method:
//inventariosearch-amb_id is the ID of one of my filterselects on the gridview
$("#inventariosearch-amb_id").on("pjax:end", function() {
$.pjax.reload({container:"#inventario_lista"}); //Reload GridView
});
Let me know if i applied wrong the method.
well, as I said I think the pjax is refreshing the whole page cause it changes my page title from this:
To this:
That's how I notice the changes and the javascript doesn't work properly anymore.
What can I do?.
My view index.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\grid\ActionColumn;
use yii\widgets\Pjax;
use yii\bootstrap4\Modal;
use app\models\Ambiente;
use app\models\TipoServicio;
use app\models\Empresa;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->registerJsFile("#web/js/inventario.js",[
'depends' => [
\yii\web\JqueryAsset::className()
]
]);
$this->title = 'Servidores';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="inventario-index">
<?php $this->beginBlock('bloque_titulo'); ?>
<div class="page-title-icon">
<i class="fa fa-archive icon-gradient bg-arielle-smile">
</i>
</div>
<div>
<?= Html::encode($this->title) ?>
<div class="page-title-subheading">
Lista de servidores
</div>
</div>
<?php $this->endBlock(); ?>
<p>
<?= Html::a('<i class="fa fa-plus"></i> AƱadir nuevo', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id'=>'inventario_lista','timeout'=> false,'clientOptions' => ['method' => 'POST','registerClientScript' => 'alert("lol")']]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'amb_id',
'value' => 'amb.amb_desc',
'filter' => Html::activeDropDownList($model, 'amb_id', ArrayHelper::map(Ambiente::find()->asArray()->all(), 'amb_id', 'amb_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
'inv_plataforma',
'inv_host_computername',
[
'attribute' => 'tise_id',
'value' => 'tise.tise_desc',
'filter' => Html::activeDropDownList($model, 'tise_id',ArrayHelper::map(TipoServicio::find()->orderby(['tise_desc'=>SORT_ASC])->asArray()->all(), 'tise_id', 'tise_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
[
'attribute' => 'emp_id',
'value' => 'emp.emp_desc',
'filter' => Html::activeDropDownList($model, 'emp_id',ArrayHelper::map(Empresa::find()->orderby(['emp_desc'=>SORT_ASC])->asArray()->all(), 'emp_id', 'emp_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
//'inv_servicio',
//'inv_ip_admin',
//'inv_ip_servicio',
//'inv_ip_nfs',
//'sad_id',
//'usu_id_responsable_sistema',
//'usu_id_2doresponsable_sistema',
//'inv_modelo_servidor',
//'prov_id',
//'inv_serial_equipo',
//'inv_codigo_remedy',
//'inv_serial_dispositivo',
//'sop_id',
//'inv_version_so',
//'inv_alta_disponibilidad',
//'inv_ubicacion',
//'inv_ala',
//'inv_fila',
//'inv_rack',
//'inv_cpu_core',
//'inv_cpu_modelo',
//'inv_cpu_velocidad',
//'inv_gb_memoria',
//'hat_id',
//'inv_tipo_contrato_proveedor',
//'inv_responsable_funcional',
//'spa_id',
//'fv_id',
//'pr_id',
//'inv_observaciones',
//'inv_performance_review',
//'inv_performance_management',
//'inv_obsoleto',
//'inv_motivo_obsoleto',
//'inv_arbol',
//'inv_arbol_1er_nivel',
//'inv_fin_venta',
//'inv_fin_partes',
//'inv_fin_soporte',
//'inv_fecha_cons_obsoleto',
['class' => 'yii\grid\ActionColumn',
'buttons'=>[
'view'=>
function($url,$model,$key){
$btn = Html::button("<i class='fa fa-eye'></i>",[
'value'=>Yii::$app->urlManager->createUrl('inventario/view/'.$key),
'class'=>'serverview grid-action btn btn-info',
'title'=>'Ver datos del servidor',
'data-toggle'=> 'modal',
'data-target'=> '#modalviewserver',
]);
return $btn;
},
'update'=>function ($url,$model,$key) {
return Html::a('<i class="fa fa-edit"></i>', ['/inventario/update/'.$key], ['class'=>'btn btn-success grid-button']);
},
],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
Modal::begin([
'title' => '<h4>Ver servidor</h4>',
'id' => 'modalviewserver',
'size' => 'modal-lg',
]);
echo "<div id='viewservercontent'></div>";
Modal::end();
?>
My action controller:
public function actionIndex()
{
$model = new InventarioSearch();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model
]);
}
And my JS (just in case):
$(document).ready(function ()
{
// $("#inventariosearch-amb_id").on("pjax:end", function() {
// $.pjax.reload({container:"#inventario_lista"}); //Reload GridView
// });
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
});
If you want your link to refresh whole page you have to remove your pjax.
Other way, try to set your javascript in pjax:success like this:
$(document).on('ready pjax:success', function(){
//your javascript here
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
})
i need to add a class and a function to a dropdownlist in Yii2 activeform, here's the code:
<?= $form->field($model, 'tipocontratto')->dropDownList(['RES' => 'Residenziale', 'BUS' => 'Business'], ['prompt'=>'Seleziona...'],['maxlenght'=> true]); ?>
I need to specify a class for the field and also a javascript function.
In normal textfield i make this way:
field($model, 'cogn_ragsoc')->textInput(['maxlength' => true,'class'=>'form-control formtesto','onfocus'=>'test()']) ?>
andd it works perfectly, but in dropdownlist it doesn't
How can i do?
This works perfectly.
<?= $form->field($model, 'tipocontratto')->dropDownList(['RES' => 'Residenziale', 'BUS' => 'Business'], ['prompt'=>'Seleziona...','class'=>'yourclass','onchange'=>'function()']); ?>
try adding options with class eg: :
<?= $form->field($model, 'tipocontratto')->dropDownList(['RES' => 'Residenziale', 'BUS' => 'Business'],
['prompt'=>'Seleziona...'],['maxlenght'=> true],
[options=> ['class' => 'yuorClass']]); ?>
Form rendered using ajax:
<?php $form = ActiveForm::begin(['id' => 'que',
'enableClientValidation' => true
]); ?>
<?php echo $form->field($model, 'fk_subject')
->dropDownList(ArrayHelper::map($subjects, 'id_subject', 'name'), [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'ng-model' => 'que.fk_subject',
'prompt' => 'Select subject',
'ng-change' => 'fillTopic(que);'
]); ?>
<?php echo $form->field($model, 'fk_topic')
->dropDownList([], [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'ng-model' => 'que.fk_topic',
'prompt' => 'Select topic',
'ng-change' => 'openAddTopic(que);',
'ng-options' => 'topic.id_subject as topic.name for topic in topics',
]); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]); ?>
<?php echo Html::submitButton('Save',
['class' => 'btn btn-primary',
'name' => 'Save']) ?>
<?php ActiveForm::end(); ?>
I loaded the above form using ajax in yii2 and problem is client side validation is not working with it. If I load the form content on window load it works fine.
OK I find the solution, I will have to use renderAjax to get the form html or will have to add beginpage and beginend function if I use renderPartial
<?php $this->beginPage(); ?>
<?php $this->beginBody(); ?>
// Form and content redenered using ajax
<?php $this->endBody(); ?>
<?php $this->endPage(); ?>
so that yii can add client validation script with the rendered content
make sure you use renderAjax() method in your controller to load this form via ajax, this way It's needed scripts will register when it loads.
other than that you need to assign a unique ID to your form to prevent possible conflicts when this form is loaded in other views.
I have a form with select input. I want to auto submit the form when the dropdown list was selected.
My code:
<?php echo $this->Form->create('Product', array('controller'=>'products', 'action'=>'shipping_area'));
echo $this->Form->input('area', array('options' => array('1' => 'Within Malaysia', '2' => 'International'), 'empty' => 'choose area',
'label' => 'Choose shipping area', 'onChange'=>'javascript:this.form.submit()'));
//echo $this->Form->end('Save');
?>
I put 'onChange'=>'javascript:this.form.submit()', but it goes to http://localhost/cake/cake/products/shipping_area ( supposely http://localhost/cake/products/shipping_area )
I also tried 'onChange'=>'this.form.submit()', but got same error.
can anyone please help.
You can add an "id" attribute to the form and then every time that you get an "onchange" event in the "select" element, you have to obtain the "id" value and pass it to the javascript function "document.getElement('idValueHere')" and call to the fuction submit. More clearly, the following code:
<?php
# step 1: add an id attribute ('id' => 'anyFormName') to the array options
# step 2: add an onchange envent to the dropdown ('onChange'=>'document.getElementById("anyFormName").submit();')
echo $this->Form->create('Product', array('controller'=>'products', 'action'=>'shipping_area', 'id' => 'anyFormName'));
echo $this->Form->input('area', array('options' => array('1' => 'Within Malaysia', '2' => 'International'), 'empty' => 'choose area',
'label' => 'Choose shipping area', 'onChange'=>'document.getElementById("anyFormName").submit();'));
//echo $this->Form->end('Save');?>
Hope it helps you.
echo $this->Form->create('Product', array(
'url' => array(
'controller'=>'products', 'action'=>'shipping_area'
)
));