Hola @rafaelrosales , muchas gracias por la respuesta, he tomado lo que me has dicho para ir organizando la aplicación. Me serviría mucho un ejemplo, como para terminar de cerrar el tema.
Mira aqui te pongo un ejemplo, en cuestión consiste en que tengo una tabla clientes y otra firmantes, relacionadas por los campos CodCliente, o sea en la tabla clientes tengo el codigo del cliente (CodCliente) y en la tabla firmantes a cada cliente le pueden corresponder varios firmantes, por lo tanto tengo tambien el campo CodCliente con una relacion uno a muchos, cuando creo un cliente en la misma forma puedo crear los firmantes de ese cliente, o actualizarlos en un momento determinado en caso que se necesite cambiar, eliminar o anexar firmantes, aqui te pongo los trozos de codigo para tu necesidad:
en el controlador de clientes creo la funcion SalvarFirmantes que es donde voy a crear el cliente con sus firmantes
public function actionSalvarFirmantes() {
$id = $_POST['modelid'];
if ($id) {
$model = $this->loadModel($id);
} else {
$model = new Clientes;
//verificar si el codigo ya existe
$fact = Clientes::model()->find('CodCliente = :fa', array(':fa' => $_POST['codcliente']));
if ($fact) {
echo "fail";
yii::app()->end();
}
}
if (isset($_POST['detalle'])) {
//Lo que se guarda en clientes
$model->CodCliente = $_POST['codcliente'];
$model->CodREUP = $_POST['codreup'];
$model->CodProv = $_POST['codprov'];
$model->CodMun = $_POST['codmun'];
$model->Descripcion = $_POST['descripcion'];
$model->Direccion = $_POST['direccion'];
$model->CodOrg = $_POST['codorg'];
$model->NIT = $_POST['nit'];
$model->NRegCom = $_POST['nregcom'];
$model->CuentaCUP = $_POST['cuentacup'];
$model->CuentaCUC = $_POST['cuentacuc'];
$model->Codsec = $_POST['codsec'];
$model->sucursal = $_POST['sucursal'];
$model->IdAlcance = $_POST['alcance'];
if ($model->save()) {
Firmantes::model()->deleteAll('CodCliente=:CodCliente', array(':CodCliente' => $model->CodCliente));
foreach ($_POST['detalle'] as $item) {
//Lo que se guarda en tabla Firmantes
$detalle = new Firmantes;
$detalle->CodCliente = $model->CodCliente;
$detalle->CI = $item['ci'];
$detalle->Nombre = $item['nombre'];
$detalle->CodUEB = $item['ueb'];
$detalle->Contrato = $item['contrato'];
$detalle->cargo = $item['cargo'];
$detalle->Fechaf = $item['fechaf'];
$detalle->save();
}
}
}
}
en forma (_form) de clientes hago este script que es para crear los clientes y los firmantes, tambien te pongo los style que utilice:
<script>
$(function() {
//Add, Save, Edit and Delete functions code
$(".btnEdit").on("click", Edit);
$(".btnDelete").on("click", Delete);
$("#btnAdd").on("click", Add);
ActualizarCodigo();
$.ajax({
url: 'index.php?r=clientes/actualizarMunicipios',
type: 'POST',
dataType: 'json',
data: {
"idCodigo": $('#Clientes_CodProv').val()
},
success: function(data) {
$("#Clientes_CodMun").html(data.municipios);
}
});
});
function Add() {
if ($('#ueb option:selected').text() !== '') {
var codigo = $('#incodigo').val() === '' ? '0' : $('#incodigo').val();
var ci = $('#inci').val() === '' ? '0' : $('#inci').val();
var nombre = $('#innombre').val() === '' ? '0' : $('#innombre').val();
var cargo = $('#incargo').val() === '' ? '0' : $('#incargo').val();
var contrato = $('#incontrato').val() === '' ? '0' : $('#incontrato').val();
var fechaf = $('#infechaf').val() === '' ? '0' : $('#infechaf').val();
var codigoUEB = $('#Clientes_CodUEB').val();
$("#tblData tbody").append(
"<tr class='even'>" +
"<td>" + codigo + "</td>" +
"<td>" + $('#ueb option:selected').text() + "</td>" +
"<td>" + ci + "</td>" +
"<td>" + nombre + "</td>" +
"<td>" + cargo + "</td>" +
"<td>" + contrato + "</td>" +
"<td>" + fechaf + "</td>" +
"<td><img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'> <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/></td>" +
"</tr>");
$(".btnEdit").off("click");
$(".btnDelete").off("click");
$(".btnEdit").on("click", Edit);
$(".btnDelete").on("click", Delete);
document.getElementById('inci').value = '';
document.getElementById('innombre').value = '';
document.getElementById('incargo').value = '';
document.getElementById('incontrato').value = '';
document.getElementById('infechaf').value = '';
// $('#ueb option:selected').remove();
ActualizarCodigo();
}
else {
alert('No quedan Fichas para adicionar');
}
}
;
var oldCI;
var oldNombre;
var oldcargo;
var oldContrato;
var oldFechaf;
function Edit() {
var par = $(this).parent().parent(); //tr
var tdCI = par.children("td:nth-child(3)");
var tdNombre = par.children("td:nth-child(4)");
var tdcargo = par.children("td:nth-child(5)");
var tdContrato = par.children("td:nth-child(6)");
var tdFechaf = par.children("td:nth-child(7)");
var tdButtons = par.children("td:nth-child(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />");
oldCI = tdCI.html();
oldNombre = tdNombre.html();
oldcargo = tdNombre.html();
oldContrato = tdContrato.html();
oldFechaf = tdFechaf.html();
tdCI.html("<input type='text' id='txtCI value='" + tdCI.html() + "'/>");
tdNombre.html("<input type='text' id='txtNombre' value='" + tdNombre.html() + "'/>");
tdcargo.html("<input type='text' id='txtcargo' value='" + tdcargo.html() + "'/>");
tdContrato.html("<input type='text' id='txtContrato' value='" + tdContrato.html() + "'/>");
tdFechaf.html("<input type='date' id='txtFechaf' value='" + tdFechaf.html() + "'/>");
tdButtons.html("<img src='images/save.png' class='btnSave' title='Guardar' style='cursor:pointer'/> <img src='images/cancel.gif' class='btnCancel' title='Cancelar' style='cursor:pointer'/>");
$(".btnEdit").off("click");
$(".btnDelete").off("click");
$(".btnSave").on("click", Save);
$(".btnCancel").on("click", Cancel);
$(".btnEdit").on("click", Edit);
$(".btnDelete").on("click", Delete);
}
;
function Save() {
var par = $(this).parent().parent(); //tr
var tdCI = par.children("td:nth-child(3)");
var tdNombre = par.children("td:nth-child(4)");
var tdcargo = par.children("td:nth-child(5)");
var tdContrato = par.children("td:nth-child(6)");
var tdFechaf = par.children("td:nth-child(7)");
var tdButtons = par.children("td:nth-child(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />");
tdCI.html(tdCI.children("input[type=text]").val());
tdNombre.html(tdNombre.children("input[type=text]").val());
tdcargo.html(tdcargo.children("input[type=text]").val());
tdContrato.html(tdContrato.children("input[type=text]").val());
tdFechaf.html(tdFechaf.children("input[type=date]").val());
tdButtons.html("<img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'/> <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/>");
$(".btnEdit").off("click");
$(".btnDelete").off("click");
$(".btnEdit").on("click", Edit);
$(".btnDelete").on("click", Delete);
}
;
function Cancel() {
var par = $(this).parent().parent(); //tr
var tdCI = par.children("td:nth-child(3)");
var tdNombre = par.children("td:nth-child(4)");
var tdcargo = par.children("td:nth-child(5)");
var tdContrato = par.children("td:nth-child(6)");
var tdFechaf = par.children("td:nth-child(7)");
var tdButtons = par.children("td:nth-child(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />");
tdCI.html(oldCI);
tdNombre.html(oldNombre);
tdcargo.html(oldcargo);
tdContrato.html(oldContrato);
tdFechaf.html(oldFechaf);
tdButtons.html("<img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'/> <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/>");
$(".btnEdit").off("click");
$(".btnDelete").off("click");
$(".btnEdit").on("click", Edit);
$(".btnDelete").on("click", Delete);
}
;
function Delete() {
var par = $(this).parent().parent(); //tr
$('#ueb')
.append($("<option></option>")
.attr("value", par.children("td:nth-child(1)").html())
.text(par.children("td:nth-child(2)").html()));
ActualizarCodigo();
par.remove();
}
;
function ActualizarCodigo() {
$('#incodigo').val($('#ueb option:selected').val());
}
;
$('#clientes-form').live('submit', function(event) {
var tbl = $('#tblData tbody tr').map(function() {
var row = $(this);
return {ueb: row.find(':nth-child(1)').text(),
ci: row.find(':nth-child(3)').text(),
nombre: row.find(':nth-child(4)').text(),
cargo: row.find(':nth-child(5)').text(),
contrato: row.find(':nth-child(6)').text(),
fechaf: row.find(':nth-child(7)').text(),
};
}).get();
$.ajax({
url: 'index.php?r=clientes/salvarFirmantes',
type: 'POST',
dataType: 'text',
data: {"detalle": tbl,
"codcliente": $('#Clientes_CodCliente').val(),
"codreup": $('#Clientes_CodREUP').val(),
"codprov": $('#Clientes_CodProv').val(),
"codmun": $('#Clientes_CodMun').val(),
"descripcion": $('#Clientes_Descripcion').val(),
"direccion": $('#Clientes_Direccion').val(),
"codsec": $('#Clientes_Codsec').val(),
"nit": $('#Clientes_NIT').val(),
"nregcom": $('#Clientes_NRegCom').val(),
"cuentacup": $('#Clientes_CuentaCUP').val(),
"cuentacuc": $('#Clientes_CuentaCUC').val(),
"codorg": $('#Clientes_CodOrg').val(),
"sucursal": $('#Clientes_sucursal').val(),
"alcance": $('#Clientes_IdAlcance').val(),
"modelid": $('#modelid').val()
},
success: function(data) {
if (data === 'fail')
alert('Ya existe un registro con ese Número de Cliente');
else
window.location.href = 'index.php?r=clientes/admin';
}
});
return false;
});
</script>
<style>
.mystyle
{
background: white;
border-collapse: collapse;
width: 80%;
border: 1px #D0E3EF solid;
}
.mystyle th, .mystyle td
{
border: 1px white solid;
padding: 0.3em;
}
.mystyle th
{
color: white;
background: #c00;
text-align: center;
}
.mystyle tr.even
{
background: #F8F8F8;
}
.mystyle tr.odd
{
background: #E5F1F4;
}
.mystyle tr.selected
{
background: #BCE774;
}
.mystyle tbody tr:hover
{
background: #ECFBD4;
}
.rojo1 {background-color: #FF0033; }
</style>
//En la misma forma te pongo los codigos para crear y al final te daras cuenta que se anexan los firmantes
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'clientes-form',
'enableAjaxValidation' => false,
));
?>
<?php echo '<input type="hidden" id="modelid" value="' . $model->CodCliente . '"/>'; ?>
<p class="note">Los campos con <span class="required">*</span> son requeridos.</p>
<?php echo $form->errorSummary($model); ?>
<table width="670" border="1">
<tr>
<td width="55" colspan="1"><span class="row">
<?php {
echo $form->labelEx($model, 'Descripcion');
?>
<?php echo $form->textArea($model, 'Descripcion', array('rows' => 1, 'cols' => 25, 'readonly' => FALSE)); ?> <?php
echo $form->error($model, 'Descripcion');
}
?></span></td>
<td width="51"><span class="row"><?php echo $form->labelEx($model, 'CodCliente'); ?> <?php echo $form->textField($model, 'CodCliente', array('size' => 8, 'maxlength' => 12)); ?> <?php echo $form->error($model, 'CodCliente'); ?></span></td>
<td><span class="row"><?php echo $form->labelEx($model, 'CodREUP'); ?> <?php echo $form->textField($model, 'CodREUP', array('size' => 8, 'maxlength' => 12)); ?> <?php echo $form->error($model, 'CodREUP'); ?></span></td>
<td><span class="row"><?php echo $form->labelEx($model, 'CuentaCUP'); ?> <?php echo $form->textField($model, 'CuentaCUP', array('size' => 14, 'maxlength' => 16)); ?> <?php echo $form->error($model, 'CuentaCUP'); ?></span></td>
<td width="8"><span class="row"><?php echo $form->labelEx($model, 'sucursal'); ?> <?php echo $form->textField($model, 'sucursal', array('size' => 12, 'maxlength' => 12)); ?> <?php echo $form->error($model, 'sucursal'); ?></span></td>
</tr>
<tr>
<td width="55" colspan="1"><span class="row">
<?php {
echo $form->labelEx($model, 'Direccion');
?>
<?php echo $form->textArea($model, 'Direccion', array('rows' => 1, 'cols' => 25, 'readonly' => FALSE)); ?> <?php
echo $form->error($model, 'Direccion');
}
?></span></td>
<td><span class="row"><?php echo $form->labelEx($model, 'CuentaCUC'); ?> <?php echo $form->textField($model, 'CuentaCUC', array('size' => 14, 'maxlength' => 16)); ?> <?php echo $form->error($model, 'CuentaCUC'); ?></span></td>
<td><span class="row"><?php echo $form->labelEx($model, 'Código NIT'); ?> <?php echo $form->textField($model, 'NIT', array('size' => 8, 'maxlength' => 12)); ?> <?php echo $form->error($model, 'NIT'); ?></span></td>
<td><span class="row"><?php echo $form->labelEx($model, 'Código Reg Comer'); ?> <?php echo $form->textField($model, 'NRegCom', array('size' => 16, 'maxlength' => 16)); ?> <?php echo $form->error($model, 'NRegCom'); ?></span></td>
<td><?php echo $form->labelEx($model, 'IdAlcance'); ?> <?php echo $form->dropDownList($model, 'IdAlcance', CHtml::listData(Alcancontrato::model()->findAll(array('order' => 'Descripcion')), 'Id', 'Descripcion'));
?> <?php echo $form->error($model, 'IdAlcance'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model, 'CodProv'); ?><span class="row"><?php
echo $form->dropDownList($model, 'CodProv', CHtml::listData(Provincias::model()->findAll(array('order' => 'Descripcion')), 'CodProv', 'Descripcion'), array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('clientes/actualizarMunicipios'),
'dataType' => 'json',
'data' => array('idCodigo' => 'js:this.value'),
'success' => 'function(data) {
$("#Clientes_CodMun").html(data.municipios);
}')
)
);
?> <?php echo $form->error($model, 'CodProv'); ?></span></td>
<td><?php echo $form->labelEx($model, 'CodMun'); ?><?php echo $form->dropDownList($model, 'CodMun', array());
?><?php echo $form->error($model, 'CodMun'); ?></td>
<td><?php echo $form->labelEx($model, 'Organismo'); ?> <?php echo $form->dropDownList($model, 'CodOrg', CHtml::listData(Xorganismos::model()->findAll(array('order' => 'Descripcion')), 'CodOrg', 'Descripcion'));
?> <?php echo $form->error($model, 'CodOrg'); ?></td>
<td><?php echo $form->labelEx($model, 'Sector'); ?> <?php echo $form->dropDownList($model, 'Codsec', CHtml::listData(Sectores::model()->findAll(array('order' => 'NSector')), 'Codsec', 'NSector'));
?> <?php echo $form->error($model, 'Codsec'); ?></td>
</tr>
</table>
<!-- ---------------------------------------- Detalles de las Fichas de Clientes ------------------------------------- -->
<fieldset>
<legend>Lista de Firmantes</legend>
<table>
<tr>
<td>
<label>Entidad</label>
<?php
$conceptos = array();
$todos = Entidades::model()->findAll(array('order' => 'NEnt'));
foreach ($todos as $ueb) {
$esta = false;
foreach ($model->firmantes as $value) {
if ($ueb->NEnt == $value->idProducto->NEnt) {
$esta = true;
break;
}
}
if (!$esta)
$conceptos[$ueb->CodUEB] = $ueb->NEnt;
}
echo CHtml::dropDownList('ueb', '', $conceptos, array(
'onChange' => 'javascript:ActualizarCodigo()',
));
?>
</td>
<td>
<label>Código UEB</label>
<input type="text" size="7" id="incodigo" readonly="true"/>
</td>
<td>
<label>CI</label>
<input type="text" maxlength="11" size="11" id="inci"/>
</td>
<td>
<label>Nombre y Apellidos</label>
<input type="text" size="30" id="innombre"/>
</td>
</tr>
<tr>
<td>
<label>Cargo</label>
<input type="text" size="30" id="incargo"/>
</td>
<td>
<label>Contrato</label>
<input type="text" size="7" id="incontrato"/>
</td>
<td>
<label>Fecha Vencimiento</label>
<input type="date" id="infechaf"/>
</td>
</tr>
<tr>
<td>
<input type="button" id="btnAdd" value="Adicionar Ficha de Cliente"/>
</td>
</tr>
</table>
<table id="tblData" class="mystyle">
<thead>
<tr>
<th>Código</th>
<th>Entidad</th>
<th>CI</th>
<th>Nombre y Apellidos</th>
<th>Cargo</th>
<th>Contrato</th>
<th>Fecha Vencimiento</th>
</tr>
</thead>
<tbody>
<?php
foreach ($model->firmantes as $value) {
echo "<tr>";
echo "<td>" . $value->idProducto->CodUEB . "</td>";
echo "<td>" . $value->idProducto->NEnt . "</td>";
echo "<td>" . $value->CI . "</td>";
echo "<td>" . $value->Nombre . "</td>";
echo "<td>" . $value->cargo . "</td>";
echo "<td>" . $value->Contrato . "</td>";
echo "<td>" . $value->Fechaf . "</td>";
echo "<td><img src='" . Yii::app()->request->baseUrl . "/images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'>
<img src='" . Yii::app()->request->baseUrl . "/images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</fieldset>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Crear' : 'Salvar'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->