Kayzen,
Me passa a ordem de cadastro, que vou montar como que deve ser feito, só que como você não usa ‘autoincremento’, como vai estipular as ID para empresa, endereco e site?
Kayzen,
Me passa a ordem de cadastro, que vou montar como que deve ser feito, só que como você não usa ‘autoincremento’, como vai estipular as ID para empresa, endereco e site?
As ids para empresa, endereco e site dentro de suas respectivas tabelas são auto incremento.
Acho que fiz confusão com esse auto incremento… rsrsr
Bom a ordem do cadastro é o seguinte:
1º Cadastro os dados do:
empresa dentro da tabela empresa
endereço dentro da tabela endereço
site dentro da tabela home
2º Cadastro dentro da tabela Cadastro os dados:
data do cadastro
idempresa
idendereco
idhome
FIM…
Kayzen,
Seguindo essa ordem vou dar um exemplo de como tem que fazer!
Primeiramente verifica nos Models de cada item, Empresa, Endereco e Home.
public function rules() {
return array(
array('id', 'required'),
}
Onde esta esse ‘id’, verifica se nesse array tem o idempresa, idendereco e idhome, e retira ele desse array(‘required’).
Por que isso? Por que todos esses campos vão ser validado na hora de inserir no banco de dados, você removendo, ele não será validado, no $var->validate()
Agora no CadastroController faz mais ou menos isso.
if(isset($_POST['Cadastro']) && isset($_POST['Empresa']) && isset($_POST['Endereco']) && isset($_POST['Home']))
{
$model->attributes = $_POST['Cadastro'];
$empresa->attributes = $_POST['Empresa'];
$endereco->attributes = $_POST['Endereco'];
$home->attributes = $_POST['Home'];
/*
* Validando os 4 models
*/
if($model->validate() && $empresa->validate() && $endereco->validate() && $home->validate()){
/*
* Salvar o Cadastro.
*/
if($empresa->save()){
/* Depois que foi salvo ele vai cair dentro dessa condição */
/* Agora vamos salvar nos outros banco de dados */
$idempresa = $model->idempresa;
$endereco = new Endereco;
$endereco->nmo_endereco = $_POST['Empresa']['nmo_endereco'];
...
$endereco->save(false);
$idendereco = $endereco->idendereco;
$home = new Home;
$home->nmo_home = $_POST['Home']['nmo_home'];
...
$home->save(false);
$idhome = $home->idhome;
$cadastro = new Cadastro;
$cadastro->data_cadastro = date('Y-m-d');
$cadastro->idempresa = $idempresa;
$cadastro->idendereco = $idendereco;
$cadastro->idhome = $idhome;
$cadastro->save(false);
$this->redirect(array('view','id'=>$model->idcadastro));
}
}
}
Esse modo é so para você ter uma base de como tem que seguir as inserções, as vezes o Daniel ou outros tem um modo mais reduzido.
Heeh, meu modo não conta. Eu não uso mais parecido com o gerado pelo crud ou pelo Gii. Eu fui adaptando pras necessidades do sistema daqui, e, hoje, está muuito diferente. Poderia esplicar, mas, pra quem ta iniciando, é melhor aprender do jeito que o Yii apresenta, é mais fácil pra aprender o uso ![]()
Mas, se ele for perguntando, vamos respondendo o que for possível ![]()
[editado]
Esqueci de dizer não tenho problemas com id pq uso UUID como chave primária das tabelas.
Bom… como o tempo anda meio curto, não mexi mais no YII e estou garrado com um sistema aqui na empresa, na verdade atrasado xD.
Agradeço ao Newerton e ao Daniel pela força que estão me dando, porém não vou poder mexer com o YII por agora, tenho que dar uma pausa e terminar um serviço. Quando eu tiver mais folgado eu volto e reabro esse tópico, se é que tem como… e continuo de onde parei… um abraço à todos!!!![]()
Boa tarde Newbie,
estou começando a trabalhar com yii e tb não tenho muita experiência com desenvolvimento web.
Vi nessa captura de tela q vc colocou os links de "operations" na horizontal. Sei que dá p0 fazer isso via css inclusive vi alguns exemplos na net, mas estou com dificuldade p/ implementar no meu sistema.
Você poderia me dizer como posso fazer p/ eu ter o mesmo resultado da sua tela???
Desde já obrigado!!
Bruno Piaui
Eae Bruno,
Sobre o menu de Operação(Operations) aquele layout e padrão do Yii.
Quando tu gerar o blog ele já posiciona daquele jeito.
Mais se tu quizer saber qual CSS que é, o layouts/main.php tem ele.
<!-- blueprint CSS framework -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
Estou com problemas para fazer o update do mesmo problema do kayzen, alguém pode me ajudar?
pode explicar o problema ? tem muita coisa nesse post pra ler
estou com o mesmo problema segui o tutorial, e fiz basicamente tudo oque foi passado.
mas os meus Id sao auto increment, mas se eu vo la e retiro o required ele da erros de validacao ![]()
kaades,
Se os ID é auto increment, é só remover o ID do da linha ‘required’ da função rules.
Onde exatamente está ocorrendo o erro?
poise eu fui no model Devedor e retirei o ‘required’.
mas dai da erro de validação.
Devedor tem uma regra de validação inválida. A regra deve especificar atributos para serem validados e o nome do validador.
Model Devedor
class Devedor extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Devedor the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'devedor';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('nome, contato_id, endereco_id'),
array('contato_id, endereco_id', 'numerical', 'integerOnly'=>true),
array('nome, apelido', 'length', 'max'=>150),
array('cpf_cnpj, ie_rg', 'length', 'max'=>45),
array('datanasc, obs', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, nome, apelido, datanasc, obs, cpf_cnpj, ie_rg, contato_id, endereco_id', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'cobrancas' => array(self::HAS_MANY, 'Cobranca', 'devedor_id'),
'contato' => array(self::BELONGS_TO, 'Contato', 'contato_id'),
'endereco' => array(self::BELONGS_TO, 'Endereco', 'endereco_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'nome' => 'Nome',
'apelido' => 'Apelido',
'datanasc' => 'Datanasc',
'obs' => 'Obs',
'cpf_cnpj' => 'Cpf Cnpj',
'ie_rg' => 'Ie Rg',
'contato_id' => 'Contato',
'endereco_id' => 'Endereco',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('nome',$this->nome,true);
$criteria->compare('apelido',$this->apelido,true);
$criteria->compare('datanasc',$this->datanasc,true);
$criteria->compare('obs',$this->obs,true);
$criteria->compare('cpf_cnpj',$this->cpf_cnpj,true);
$criteria->compare('ie_rg',$this->ie_rg,true);
$criteria->compare('contato_id',$this->contato_id);
$criteria->compare('endereco_id',$this->endereco_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
DevedorController
public function actionCreate() {
$model = new Devedor;
$contato = new Contato;
$endereco = new Endereco;
$cidade = new Cidade;
$estado = new Estado;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($model, $cidade, $contato, $endereco, $estado));
if (isset($_POST['Devedor']) && isset($_POST['Contato']) && isset($_POST['Endereco']) && isset($_POST['Cidade']) && isset($_POST['Estado'])) {
$model->attributes = $_POST['Devedor'];
$cidade->attributes = $_POST['Cidade'];
$contato->attributes = $_POST['Contato'];
$endereco->attributes = $_POST['Endereco'];
$estado->attributes = $_POST['Estado'];
if ($model->validate() && $cidade->validate() && $contato->validate() && $endereco->validate() && $estado->validate()) {
if ($model->save() && $cidade->save() && $contato->save() && $endereco->save() && $estado->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
}
$this->render('create', array(
'model' => $model,
'cidade'=> $cidade,
'contato'=> $contato,
'endereco'=>$endereco,
'estado'=>$estado,
));
}
_Form do devedor
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'devedor-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'apelido'); ?>
<?php echo $form->textField($model,'apelido',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'apelido'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'datanasc'); ?>
<?php echo $form->textField($model,'datanasc'); ?>
<?php echo $form->error($model,'datanasc'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cpf_cnpj'); ?>
<?php echo $form->textField($model,'cpf_cnpj',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'cpf_cnpj'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'ie_rg'); ?>
<?php echo $form->textField($model,'ie_rg',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'ie_rg'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'logradouro'); ?>
<?php echo $form->textField($endereco,'logradouro',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($endereco,'logradouro'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'numero'); ?>
<?php echo $form->textField($endereco,'numero'); ?>
<?php echo $form->error($endereco,'numero'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'bairro'); ?>
<?php echo $form->textField($endereco,'bairro',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($endereco,'bairro'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'cep'); ?>
<?php echo $form->textField($endereco,'cep'); ?>
<?php echo $form->error($endereco,'cep'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($cidade,'descricao'); ?>
<?php echo $form->textField($cidade,'descricao',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($cidade,'descricao'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($estado,'uf'); ?>
<?php echo $form->textField($estado,'uf',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($estado,'uf'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'email'); ?>
<?php echo $form->textField($contato,'email',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($contato,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'fone'); ?>
<?php echo $form->textField($contato,'fone',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($contato,'fone'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'celular'); ?>
<?php echo $form->textField($contato,'celular',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($contato,'celular'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'obs'); ?>
<?php echo $form->textArea($model,'obs',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'obs'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
create.php Devedor
<h1>Create Devedor</h1>
<?php echo $this->renderPartial('_form', array('model'=>$model, 'contato'=>$contato, 'cidade'=>$cidade, 'endereco'=>$endereco, 'estado'=>$estado)); ?>
Kaades,
Não remove o ‘required’.
O ‘required’, é um atributo que define quais campos precisa ser validados.
Olha o erro seu aqui:
array('nome, contato_id, endereco_id'),
Volta o ‘required’:
array('nome, contato_id, endereco_id', 'required'),
Se retorna o erro, posta aqui.
Tem muita coisa pra corrigir ae.
ao clicar em create
Aparece o seguinte erro.
Object of class Contato could not be converted to string
DevedorController
public function actionCreate()
{
$model=new Devedor;
$contato = new Contato;
$endereco = new Endereco;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model,$contato,$endereco);
if(isset($_POST['Devedor']) && isset($_POST['Contato']) && isset($_POST['Endereco']))
{
$model->attributes=$_POST['Devedor'];
$contato->attributes=$_POST['Contato'];
$endereco->attributes=$_POST['Endereco'];
if($model->validate()){
$model->save();
}
if($contato->validate()){
$contato->id = $model->contato_id;
$contato->save();
}
if($endereco->validate()){
$endereco->id = $model->endereco_id;
$endereco->save();
}
if($model->validate() && $contato->validate() && $endereco->validate()){
$this->redirected(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
'contato'=>$contato,
'endereco'=>$endereco,
));
}
_form
<?php
/* @var $this DevedorController */
/* @var $model Devedor */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'devedor-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model,$contato,$endereco); ?>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'apelido'); ?>
<?php echo $form->textField($model,'apelido',array('size'=>60,'maxlength'=>150)); ?>
<?php echo $form->error($model,'apelido'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'datanasc'); ?>
<?php echo $form->textField($model,'datanasc'); ?>
<?php echo $form->error($model,'datanasc'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cpf_cnpj'); ?>
<?php echo $form->textField($model,'cpf_cnpj',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'cpf_cnpj'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'ie_rg'); ?>
<?php echo $form->textField($model,'ie_rg',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'ie_rg'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'endereco_id'); ?>
<?php echo $form->textField($model,'endereco_id'); ?>
<?php echo $form->error($model,'endereco_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'logradouro'); ?>
<?php echo $form->textField($endereco,'logradouro'); ?>
<?php echo $form->error($endereco,'logradouro'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'numero'); ?>
<?php echo $form->textField($endereco,'numero'); ?>
<?php echo $form->error($endereco,'numero'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'bairro'); ?>
<?php echo $form->textField($endereco,'bairro'); ?>
<?php echo $form->error($endereco,'bairro'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'cep'); ?>
<?php echo $form->textField($endereco,'cep'); ?>
<?php echo $form->error($endereco,'cep'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'cidade'); ?>
<?php echo $form->textField($endereco,'cidade'); ?>
<?php echo $form->error($endereco,'cidade'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($endereco,'estado_id'); ?>
<?php echo $form->textField($endereco,'estado_id'); ?>
<?php echo $form->error($endereco,'estado_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'contato_id'); ?>
<?php echo $form->textField($model,'contato_id'); ?>
<?php echo $form->error($model,'contato_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'email'); ?>
<?php echo $form->textField($contato,'email'); ?>
<?php echo $form->error($contato,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'fone'); ?>
<?php echo $form->textField($contato,'fone'); ?>
<?php echo $form->error($contato,'fone'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($contato,'celular'); ?>
<?php echo $form->textField($contato,'celular'); ?>
<?php echo $form->error($contato,'celular'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'tipo_id'); ?>
<?php echo $form->textField($model,'tipo_id'); ?>
<?php echo $form->error($model,'tipo_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'obs'); ?>
<?php echo $form->textArea($model,'obs',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'obs'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
create.php
<?php
/* @var $this DevedorController */
/* @var $model Devedor */
$this->breadcrumbs=array(
'Devedors'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List Devedor', 'url'=>array('index')),
array('label'=>'Manage Devedor', 'url'=>array('admin')),
);
?>
<h1>Create Devedor</h1>
<?php $this->renderPartial('_form', array('model'=>$model, 'contato'=>$contato, 'endereco'=>$endereco)); ?>
Olá
Tentei seguir o Post porque quero inserir dados de duas tabelas no mesmo form, tenho a tabela Pessoa(pessoa_id,nome,data_nascimento,sexo) documento(documento_id,numero,data_emissao,data_validade,pessoa_id), queria inserir no form pessoa os dados do documento. Mas tenho o seguinte erro
Create Pessoa
Fields with * are required.
Fatal error: Call to a member function getErrors() on a non-object in C:\xampp\htdocs\yii\framework\web\helpers\CHtml.php on line 1765
O ControllerPessoa
public function actionCreate(){
$model = new Pessoa;
$documento = new Documento;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation(array($model,$documento));
if( isset($_POST['Pessoa']) && isset($_POST['Documento']))
{
$model->attributes=$_POST['Pessoa'];
$documento->attributes=$_POST['Documento'];
if ($model->validate())
{
$model->save();
}
if ($documento->validate())
{
$documento->pessoa_id = $model->pessoa_id;
$documento->save();
}
if ($model->validate() && $documento->validate() )
{
$this->redirect(array('view','id'=>$model->pessoa_id));
}
}
$this->render('create',array(
'model'=>$model,
'documento'=>$documento,
));
}
A view CREATE
<?php
/* @var $this PessoaController */
/* @var $model Pessoa */
$this->breadcrumbs=array(
'Pessoas'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List Pessoa', 'url'=>array('index')),
array('label'=>'Manage Pessoa', 'url'=>array('admin')),
);
?>
<h1>Create Pessoa</h1>
<?php echo $this->renderPartial(’_form’, array(‘pessoa’=>$model, ‘documento’=>$documento)); ?>
A view do FORM
<?php
/* @var $this PessoaController */
/* @var $model Pessoa */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget(‘CActiveForm’, array(
'id'=>'pessoa-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'tipo_pessoa'); ?>
<?php echo $form->DropDownList($model,'tipo_pessoa',array('1'=>'vitima','2'=>'agressor','3'=>'denuciante','4'=>'funcionario')); ?>
<?php echo $form->error($model,'tipo_pessoa'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pessoa_nome'); ?>
<?php echo $form->textField($model,'pessoa_nome',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'pessoa_nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'data_nascimento'); ?>
<?php echo $form->textField($model,'data_nascimento'); ?>
<?php echo $form->error($model,'data_nascimento'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'sexo'); ?>
<?php echo $form->DropDownList($model,'sexo',array('1'=>'F','2'=>'M')); ?>
<?php echo $form->error($model,'sexo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'estado_civil'); ?>
<?php echo $form->DropDownList($model,'estado_civil',array('1'=>'Casado','2'=>'Solteriro')); ?>
<?php echo $form->error($model,'estado_civil'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($documento,'tipo_doc'); ?>
<?php echo $form->textField($documento,'tipo_doc'); ?>
<?php echo $form->error($documento,'tipo_doc'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($documento,'data_emissao'); ?>
<?php echo $form->textField($documento,'data_emissao'); ?>
<?php echo $form->error($documento,'data_emissao'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($documento,'data_validade'); ?>
<?php echo $form->textField($documento,'data_validade'); ?>
<?php?>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Pessoal,
Sou iniciante no yii tbm, e esse tópico ja me ajudou bastante, pois consigo exibir todos os campos de minhas tabelas, porém não vi nos comentarios como resolveram o problema de clicar para inserir e simplesmente não acontecer nada.
Em um relacionamento do meu banco tenho tres tabelas ‘FUNCIONARIO’, “FUNCIONARIO_DESEMPENHA_FUNCAO” e “FUNCAO”. tenho esse modelo pq a tabela “FUNCIONARIO_DESEMPENHA_FUNCAO”, contem os dados de inicio e fim da função, e todas essas informações faz ligação com uma outra tabela que efetua um atendimento, basicamente “um funcaionario que desempenha uma funcao efetua um atendimento”.
A ideia é que eu inclua os dados de FUNCIONARIO e FUNCIONARIO_DESEMPENHA_FUNCAO em uma so página.
No meu caso consegui deixar todos os itens que preciso inserir no create e no _form e apareceu na tela normalmente, ainda inseri um dropdown no campo "CODIGO_FUNCAO" para ja aparecer ao usuario as funções(Cargos) que já estão cadastradas, porém ao clicar em inserir todos so campos apagam o que está digitado e não insere no banco.
Se alguem puder me ajudar agradeço demais, pois ja quebrei muita cabeça 
Segue minhas páginas
FuncionarioController
<?php
class FuncionarioController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'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('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new FUNCIONARIO;
$modelFDF=new FUNCIONARIO_DESEMPENHA_FUNCAO;
$funcao=new FUNCAO;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['FUNCIONARIO']) && isset($_POST['FUNCIONARIO_DESEMPENHA_FUNCAO']) && isset($_POST['FUNCAO']))
{
$model->attributes=$_POST['FUNCIONARIO'];
$modelFDF->attributes=$_POST['FUNCIONARIO_DESEMPENHA_FUNCAO'];
$model->attributes=$_POST['FUNCAO'];
if($model->validate() && $modelFDF->validate() && $funcao->validate()){
$model->save();
$modelFDF->save();
$funcao->save();
}
$this->redirect(array('view','id'=>$model->MATRICULA));
}
$criteria = new CDbCriteria();
//$criteria->order = "CODIGO ASC";
$funcao = CHtml::listData(FUNCAO::model()->findAll($criteria), 'CODIGO', 'DESCRICAO');
$this->render('create',array(
'model'=>$model,
'modelFDF'=>$modelFDF,
'funcao'=>$funcao
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['FUNCIONARIO']))
{
$model->attributes=$_POST['FUNCIONARIO'];
if($model->save())
$this->redirect(array('view','id'=>$model->MATRICULA));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// 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('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('FUNCIONARIO');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new FUNCIONARIO('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['FUNCIONARIO']))
$model->attributes=$_GET['FUNCIONARIO'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return FUNCIONARIO the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=FUNCIONARIO::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param FUNCIONARIO $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='funcionario-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Model Funcionario
<?php
/**
* This is the model class for table "FUNCIONARIO".
*
* The followings are the available columns in table 'FUNCIONARIO':
* @property string $MATRICULA
* @property string $LOTACAO
* @property string $TELEFONE
* @property string $EMAIL
* @property string $NOME
* @property string $COD_EQUIPE
*/
class FUNCIONARIO extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'FUNCIONARIO';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('MATRICULA, EMAIL, COD_EQUIPE', 'required'),
array('LOTACAO, EMAIL, NOME', 'length', 'max'=>256),
array('TELEFONE', 'length', 'max'=>11),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('MATRICULA, LOTACAO, TELEFONE, EMAIL, NOME, COD_EQUIPE', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'FK_FUNCIONARIO_FDF'=>array(self::HAS_ONE,'FUNCIONARIO_DESEMPENHA_FUNCAO','ID'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'MATRICULA' => 'Matricula',
'LOTACAO' => 'Lotacao',
'TELEFONE' => 'Telefone',
'EMAIL' => 'Email',
'NOME' => 'Nome',
'COD_EQUIPE' => 'Cod Equipe',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('MATRICULA',$this->MATRICULA,true);
$criteria->compare('LOTACAO',$this->LOTACAO,true);
$criteria->compare('TELEFONE',$this->TELEFONE,true);
$criteria->compare('EMAIL',$this->EMAIL,true);
$criteria->compare('NOME',$this->NOME,true);
$criteria->compare('COD_EQUIPE',$this->COD_EQUIPE,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return FUNCIONARIO the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
View ‘_form’ Funcionario
<?php
/**
* This is the model class for table "FUNCIONARIO".
*
* The followings are the available columns in table 'FUNCIONARIO':
* @property string $MATRICULA
* @property string $LOTACAO
* @property string $TELEFONE
* @property string $EMAIL
* @property string $NOME
* @property string $COD_EQUIPE
*/
class FUNCIONARIO extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'FUNCIONARIO';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('MATRICULA, EMAIL, COD_EQUIPE', 'required'),
array('LOTACAO, EMAIL, NOME', 'length', 'max'=>256),
array('TELEFONE', 'length', 'max'=>11),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('MATRICULA, LOTACAO, TELEFONE, EMAIL, NOME, COD_EQUIPE', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'FK_FUNCIONARIO_FDF'=>array(self::HAS_ONE,'FUNCIONARIO_DESEMPENHA_FUNCAO','ID'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'MATRICULA' => 'Matricula',
'LOTACAO' => 'Lotacao',
'TELEFONE' => 'Telefone',
'EMAIL' => 'Email',
'NOME' => 'Nome',
'COD_EQUIPE' => 'Cod Equipe',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('MATRICULA',$this->MATRICULA,true);
$criteria->compare('LOTACAO',$this->LOTACAO,true);
$criteria->compare('TELEFONE',$this->TELEFONE,true);
$criteria->compare('EMAIL',$this->EMAIL,true);
$criteria->compare('NOME',$this->NOME,true);
$criteria->compare('COD_EQUIPE',$this->COD_EQUIPE,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return FUNCIONARIO the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
View 'create’Funcionario
<?php
/* @var $this FuncionarioController */
/* @var $model FUNCIONARIO */
$this->breadcrumbs=array(
'Funcionarios'=>array('index'),
'Inserir',
);
$this->menu=array(
array('label'=>'Exibir Funcionarios', 'url'=>array('index')),
array('label'=>'Gerenciar Funcionarios', 'url'=>array('admin')),
);
?>
<h1>Inserir Funcionario</h1>
<?php $this->renderPartial('_form', array('model'=>$model, 'modelFDF'=>$modelFDF, 'funcao'=>$funcao)); ?>
model FUNCIONARIO_DESEMPENHA_FUNCAO
<?php
/**
* This is the model class for table "FUNCIONARIO_DESEMPENHA_FUNCAO".
*
* The followings are the available columns in table 'FUNCIONARIO_DESEMPENHA_FUNCAO':
* @property string $ID
* @property string $DATA_INICIO
* @property string $DATA_FIM
* @property string $MATRICULA_FUNCIONARIO
* @property string $CODIGO_FUNCAO
*/
class FUNCIONARIO_DESEMPENHA_FUNCAO extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'FUNCIONARIO_DESEMPENHA_FUNCAO';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('ID, DATA_INICIO, MATRICULA_FUNCIONARIO, CODIGO_FUNCAO', 'required'),
array('DATA_FIM', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('ID, DATA_INICIO, DATA_FIM, MATRICULA_FUNCIONARIO, CODIGO_FUNCAO', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'FK_FDF_FUNCIONARIO'=>array(self::HAS_MANY,'FUNCIONARIO','ID'),
'FK_FDF_FUNCAO'=>array(self::HAS_ONE,'FUNCAO','CODIGO_FUNCAO'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'ID' => 'ID',
'DATA_INICIO' => 'Data Início',
'DATA_FIM' => 'Data Fim',
'MATRICULA_FUNCIONARIO' => 'Matricula Funcionário',
'CODIGO_FUNCAO' => 'Código Função',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('ID',$this->ID,true);
$criteria->compare('DATA_INICIO',$this->DATA_INICIO,true);
$criteria->compare('DATA_FIM',$this->DATA_FIM,true);
$criteria->compare('MATRICULA_FUNCIONARIO',$this->MATRICULA_FUNCIONARIO,true);
$criteria->compare('CODIGO_FUNCAO',$this->CODIGO_FUNCAO,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return FUNCIONARIO_DESEMPENHA_FUNCAO the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
De qualquer forma muito obrigado
Marcola,
Vou colocar aqui como faço inserções desta natureza, talvez possa lhe ajudar. Primeiramente, eu não uso o Gii nativo, utilizo-o junto com a extensão Giix. Esta extensão (desenvolvida pelo Rodrigo Coelho) provê uma série de métodos que ajudam um pouco a nossa vida.
Primeiramente, na visão, usaria um multiselect para poder associar as funções ao funcionario:
$this->widget(
'application.extensions.emultiselect.EMultiSelect',
array('sortable' => true, 'searchable' => true)
);
echo CHtml::dropDownList(
'FUNCIONARIO[FK_FUNCIONARIO_FDF]', //nome do campo Model[relation]
CHtml::listData(FUNCIONARIO_DESEMPENHA_FUNCAO::model()->findAllByAttributes(array(
'MATRICULA_FUNCIONARIO' => $model->MATRICULA)),
'ID', 'ID'), //models selecionados
CHtml::listData(FUNCAO::model()->findAll(),
'ID_FUNCAO', 'DESCRICAO_FUNCAO'), // models possíveis
array('multiple' => 'multiple',
'key' => 'ID', 'class' => 'multiselect')
);
?>
No model FUNCIONARIO, incluiria o método pivotModels:
public function pivotModels()
{
return array(
// relação => model de ligação
'FK_FUNCIONARIO_FDF' => 'FUNCIONARIO_DESEMPENHA_FUNCAO',
);
}
No FuncionarioController, método actionCreate, você utilizaria o método "getRelatedData" do GxController para pegar os dados relacionados do form:
$relacionados = $this->getRelatedData($_POST['FUNCIONARIO'],
$model->relations());
e depois salvaria com o método "saveWithRelated" (ao inves do "save") do GxActiveRecord:
$model->saveWithRelated($relacionados)
Obs: Faltou você compartilhar o model FUNCAO;
Obs2: Veja sua relation "FK_FUNCIONARIO_FDF", não seria "HAS_MANY" ao inves de "HAS_ONE"?
Obs3: Como você está começando, sugiro dar uma lida nesta wiki.
Espero ter ajudado.
Olá Fábio,
Primeiro, muito obrigado pela ajuda.
Então dei uma lida sobre o giix, achei interessante, o problema é que esse é meu tcc, e vou ter que ir ajustando tudo de novo se for o caso de gerar os cruds novamente… Como tenho que apresentar dia 28/02, acho que fica meio que inviável para mim… ou posso utilizar esses metodos sem instalar a extensão?
Então quanto ao relacionamento acho q é "HAS_ONE" mesmo, pois um funcionário so pode desempenhar uma função… Ou estou com a lógica errada?
a maneira que fiz o dropdown, foi com outro exemplo também que achei em um blog e o forum não deixa eu postar o link
quanto a padronização, das tebelas que vc mandou no link, tinha lido quando estava descobrindo o yii, mas a documentação do tcc ja tava pronta, e se eu fizesse diferente do que tinha nos modelos de DB os professores iriam encher o saco…rsrsrs
de qualquer forma segue o model de FUNCAO
<?php
/**
* This is the model class for table "FUNCAO".
*
* The followings are the available columns in table 'FUNCAO':
* @property string $CODIGO
* @property string $DESCRICAO
*/
class FUNCAO extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'FUNCAO';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('CODIGO, DESCRICAO', 'required'),
array('DESCRICAO', 'length', 'max'=>256),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('CODIGO, DESCRICAO', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'FK_FUNCAO_FDF'=>array(self::HAS_MANY,'FUNCIONARIO_DESEMPENHA_FUNCAO','CODIGO_FUNCAO'),
);
}
/**
* @return array para customização das label's "apelido" da coluna (name=>label)
*/
public function attributeLabels()
{
return array(
'CODIGO' => 'Codigo',
'DESCRICAO' => 'Descricao',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('CODIGO',$this->CODIGO,true);
$criteria->compare('DESCRICAO',$this->DESCRICAO,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return FUNCAO the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Enquanto isso vou tentando descobrir aqui rsrsrs
Vlw demais!
Aproveitando o próximo passo vai ser os relatórios do meu sistema, recomenda alguma leitura?
Muito Obrigado.
Marcola,
Realmente, pra TCC, vai ter de correr bastante rs. Mas se você usar o Giix, não precisa gerar novamente os cruds, apenas mudar a superclasse dos seus controladores e models (ex: Os controladores herdarem de GxController ao invés de Ccontroller, e os models herdarem de GxActiveRecord ao invés de CActiveRecord).
Em relação aos relatórios, sempre foi um problema pra mim também. O que estou fazendo é exportando os grids para excel, o que já quebra um galho. Mas quando se trata de PDF… rs