Buen dia Duos
Te comento que a la final no pude implementar la extension que me comentaste pero lo realice a patica por mi cuenta.
Te muestro
ASi quedo mi _form
<!--Generated using Gimme CRUD freeware from www.HandsOnCoding.net -->
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'top-websites-cr-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => false,
),
));
?>
<?php
Yii::app()->clientScript->registerScript("variable",
'
var articulos = [];
var cantidades = [];
var descripciones = [];
');
?>
<?php
if (defined(Yii::app()->getSession()->get('guardar_datos'))) {
Yii::app()->clientScript->registerScript("alert",
" alert('Los artículos registrados han sido guardado con exito');
");
Yii::app()->getSession()->remove('guardar_datos');
}
if (isset($_POST['Sc09ArticuloArea'])) {
$articulo_cod = explode(',', $_POST['Sc09ArticuloArea']['articulo_cod']);
$cantidad = explode(',', $_POST['Sc09ArticuloArea']['cantidad']);
$descripcion = explode(',', $_POST['descripcion']);
Yii::app()->clientScript->registerScript("inicializando",
"
articulos = " . CJSON::encode($articulo_cod) . ";
cantidades = " . CJSON::encode($cantidad) . ";
descripciones = " . CJSON::encode($descripcion) . ";
");
}
?>
<?php
Yii::app()->clientScript->registerScript("addArticle",
'
function callAjax(){
if (articulos.length > 0) {
//alert(articulos.length);
jQuery.ajax({
url: "index?r=Sc09ArticuloArea/addList",
type: "POST",
data: { articulo_cod : articulos, cantidad : cantidades, descripcion : descripciones},
success: function(data)
{
$(\'#ListaArticulos\').html(data);
},
});
}
}
$(".addArticle").click(function(){
var art = document.getElementById("articulo").value;
var cant = document.getElementById("cantidad").value;
var desc = document.getElementById("nom_articulo").value;
if (!/^([0-9])*$/.test(cant)) {
alert("El valor suministrado en el campo cantidad no es un numero entero.")
document.getElementById("cantidad").focus();
}else if (art != "" && cant != "") {
var x = articulos.indexOf(art);
if (x >= 0) {
cantidades[x] = parseInt(cant) + parseInt(cantidades[x]);
} else {
articulos.push(art);
cantidades.push(cant);
descripciones.push(desc);
}
art = "";
cant = "";
desc = "";
for (var i=0; i < articulos.length ; i++) {
art += " - " + articulos[i];
cant += " - " + cantidades[i];
desc += " - " + descripciones[i];
}
//alert(art + " ** " + cant +" **** " + desc);
document.getElementById("nom_articulo").value = "";
document.getElementById("cantidad").value = "";
document.getElementById("vec_cant").value = cantidades;
document.getElementById("articulo").value = articulos;
document.getElementById("descripcion").value = descripciones;
//alert(document.getElementById("articulo").value+" "+document.getElementById("vec_cant").value);
callAjax();
}else{
alert("Debe cargar el campo artículo y cantidad");
}
return false;
});
callAjax();
$(document).on("click", ".eliminar", function (event) {
event.preventDefault();
var element = $(this).attr("id");
articulos.splice(element, 1);
cantidades.splice(element, 1);
descripciones.splice(element, 1);
document.getElementById("vec_cant").value = cantidades;
document.getElementById("articulo").value = articulos;
document.getElementById("descripcion").value = descripciones;
$(this).closest("tr").remove();
});
');
?>
<p class="note">Los campos con <span class="required">*</span> son obligatorios.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model, 'ano_escolar_cod'); ?>
<?php echo $form->dropDownList($model, 'ano_escolar_cod', CHtml::listData(Sc05AnoEscolar::model()->findAll(), 'cod_anoEscolar', 'descripcion'), array('prompt' => 'Seleccione...')); ?>
<?php echo $form->error($model, 'ano_escolar_cod'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'responsable_cod'); ?>
<?php echo $form->dropDownList($model, 'responsable_cod', CHtml::listData(Sc06Responsable::model()->findAll('Estado="Habilitado"'), 'cod_responsable', 'nombre', 'apellido'), array('prompt' => 'Seleccione...')); ?>
<?php echo CHtml::link('Crear nuevo responsable', array('Sc06Responsable/create', 'comeback' => 'yes')); ?>
<?php echo $form->error($model, 'responsable_cod'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'area_cod'); ?>
<?php echo $form->dropDownList($model, 'area_cod', CHtml::listData(Sc04Area::model()->findAll(), 'cod_area', 'nombre'), array('prompt' => 'Seleccione...')); ?>
<?php echo CHtml::link('Crear nueva área', array('sc04Area/create', 'comeback' => 'yes')); ?>
<?php echo $form->error($model, 'area_cod'); ?>
</div>
<div class="form-inline row">
<div class="col-md-12">
<?php echo $form->labelEx($model, 'articulo_cod'); ?>
<?php echo $form->hiddenField($model, 'articulo_cod', array('id' => 'articulo')); // Campo oculto para guardar el ID de la persona seleccionada ?>
<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'nom_articulo', // Nombre para el campo de autocompletar
'model' => $model,
'value' => $model->isNewRecord ? '' : $model->articulo_cod,
'source' => $this->createUrl('Sc09ArticuloArea/autocomplete'), // URL que genera el conjunto de datos
'options' => array(
'showAnim' => 'fold',
'size' => '30',
'minLength' => '1', // Minimo de caracteres que hay que digitar antes de relizar la busqueda
'select' => "js:function(event, ui) {
$('#articulo').val(ui.item.id); // HTML-Id del campo
}",
),
'htmlOptions' => array(
'size' => 60,
'placeholder' => 'Buscar artículo...',
),
));
?>
<?php echo $form->labelEx($model, 'cantidad'); ?>
<?php echo CHtml::textField('Text', '', array('size' => 45, 'maxlength' => 45, 'class' => 'cantidad', 'id' => 'cantidad')); ?>
<?php echo $form->hiddenField($model, 'cantidad', array('id' => 'vec_cant')); // Campo oculto para guardar el ID de la persona seleccionada ?>
<?php echo CHtml::hiddenField('descripcion', '', array('id' => 'descripcion')); // Campo oculto para guardar el ID de la persona seleccionada ?>
<?php echo CHtml::link('Agregar elemento a la lista', array('#'), array('class' => 'addArticle')); ?>
</div>
</div>
<?php echo $form->error($model, 'articulo_cod'); ?>
<?php echo $form->error($model, 'cantidad'); ?>
<div id="ListaArticulos">
</div>
<br>
<div class="row buttons">
<?php echo CHtml::submitButton('Guardar en el inventario', array('class' => 'btn btn-primary')); ?>
</div>
<?php $this->endWidget();?>
</div><!-- form -->
La vista donde cargo la tabla quedo asi
<div class="row">
<table class="TapGrid" style="width: 750px;">
<thead>
<tr>
<th>Detalle</th>
<th >Cantidad</th>
<th ></th>
</tr>
</thead>
<?php
echo '<tbody>';
for ($i = 0; $i < count($codigo); $i++) {
echo '<tr id="' . $i . '">';
echo '<td>' . $descripcion[$i] . '</td>';
echo '<td>' . $cantidad[$i] . '</td>';
echo '<td>' . CHtml::link("Eliminar", "#", array('class' => 'eliminar', 'id' => $i)) . '</td>';
echo '</tr>';
}
echo '</tr></tbody>';
?>
</table>
</div>
Mi controller quedo asi
<?php
class Sc09ArticuloAreaController extends Controller {
public $layout = '//layouts/column2';
public $ListaArticulos, $i;
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view', 'autocomplete'),
'users' => array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions' => array('create', 'update', 'addList'),
'users' => array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions' => array('admin', 'delete'),
'users' => array('admin'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
public function actionIndex() {
$i = 0;
$model = new Sc09ArticuloArea;
$model_articulo = new Sc08Articulo;
if (isset($_POST['ajax']) && $_POST['ajax'] === 'client-account-create-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
if (isset($_POST['Sc09ArticuloArea'])) {
#echo CHtml::encode(print_r($_POST, true));
$model->attributes = $_POST['Sc09ArticuloArea'];
if ($model->validate()) {
$articulo_cod = explode(',', $_POST['Sc09ArticuloArea']['articulo_cod']);
$cantidad = explode(',', $_POST['Sc09ArticuloArea']['cantidad']);
$descripcion = explode(',', $_POST['descripcion']);
$i = 0;
while ($i < count($cantidad)) {
$model->articulo_cod = $articulo_cod[$i];
$model->cantidad = $cantidad[$i];
$findPk = Sc09ArticuloArea::model()->findByPk(array('articulo_cod' => $model->articulo_cod, 'area_cod' => $model->area_cod));
if ($findPk == null) {
$this->saveModel($model);
} else {
$findPk->cantidad += $model->cantidad;
$findPk->responsable_cod = $model->responsable_cod;
$findPk->ano_escolar_cod = $model->ano_escolar_cod;
$findPk->save();
}
$model->isNewRecord = true;
$i++;
}
Yii::app()->getSession()->add('guardar_datos', 'true');
$this->redirect('index', array('model' => $model, 'model_articulo' => $model_articulo));
}
}
$this->render('index', array('model' => $model, 'model_articulo' => $model_articulo));
}
public function actionAddList() {
$this->renderPartial('_listarArticulos', array('codigo' => $_POST['articulo_cod'], 'cantidad' => $_POST['cantidad'], 'descripcion' => $_POST['descripcion']));
Yii::app()->end();
}
public function actionAutocomplete($term) {
$criteria = new CDbCriteria;
$criteria->compare('LOWER(nombre)', strtolower($_GET['term']), true);
$criteria->order = 'nombre';
$criteria->limit = 30;
$data = Sc08Articulo::model()->findAll($criteria);
if (!empty($data)) {
$arr = array();
foreach ($data as $item) {
$arr[] = array(
'id' => $item->cod_articulo,
'value' => $item->nombre . ' - ' . $item->descripcion . ' - Color: ' . $item->colorCod->descripcion . '. Modo Entrada: ' . $item->modoEntradaCod->descripcion,
'label' => $item->nombre . ' - ' . $item->descripcion . ' - Color: ' . $item->colorCod->descripcion . '. Modo Entrada: ' . $item->modoEntradaCod->descripcion,
);
}
} else {
$arr = array();
$arr[] = array(
'id' => '',
'value' => 'No se han encontrado resultados para su búsqueda',
'label' => 'No se han encontrado resultados para su búsqueda',
);
}
echo CJSON::encode($arr);
}
public function actionCreateResponsable() {
$model = Sc06Responsable::model();
$model_usuario = Sc07Usuario::model();
$this->render('/sc06Responsable/create', array('model' => $model, 'model_usuario' => $model_usuario));
}
public function actionCallArea() {
$model_aa = Sc04Area::model()->findAll();
$this->renderPartial('/sc04Area/_form', array('model' => $model_aa));
}
public function actionCreate() {
$model = new Sc09ArticuloArea;
if (isset($_POST['ajax']) && $_POST['ajax'] === 'client-account-create-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
if (isset($_POST['Sc09ArticuloArea'])) {
$model->attributes = $_POST['Sc09ArticuloArea'];
if ($model->validate()) {
$this->saveModel($model);
$this->redirect(array('view', 'articulo_cod' => $model->articulo_cod, 'area_cod' => $model->area_cod));
}
}
$this->render('create', array('model' => $model));
}
public function actionDelete($articulo_cod, $area_cod) {
if (Yii::app()->request->isPostRequest) {
try
{
// we only allow deletion via POST request
$this->loadModel($articulo_cod, $area_cod)->delete();
} catch (Exception $e) {
$this->showError($e);
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
}
} else {
throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
}
}
public function loadModel($articulo_cod, $area_cod) {
$model = Sc09ArticuloArea::model()->findByPk(array('articulo_cod' => $articulo_cod, 'area_cod' => $area_cod));
if ($model == null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
return $model;
}
public function saveModel($model) {
try
{
$model->save();
} catch (Exception $e) {
$this->showError($e);
}
}
function showError(Exception $e) {
if ($e->getCode() == 23000) {
$message = "This operation is not permitted due to an existing foreign key reference.";
} else {
$message = "Invalid operation.";
}
throw new CHttpException($e->getCode(), $message);
}
}
Al modelo no le realice cambios, espero que asi como me ayudaste a tratar de solventar mi inconveniente esto le ayude a otros