RB
Dificuldade em salvar check da grid
Olá,
Pessoal, estou não estou conseguindo pegar os itens (valores )checks da grid, algumé pode me ajudar ?
segue código abaixo.
Pessoal, estou não estou conseguindo pegar os itens (valores )checks da grid, algumé pode me ajudar ?
segue código abaixo.
- <?php
- class SystemGroupBuilder extends TPage
- {
- protected $form;
- protected $form_grupo;
- protected $load;
- protected $load1;
- protected $datagrid;
- protected $cartgrid;
- protected $datagrid_group;
- protected $datagrid_user;
- protected $datagrid_alocacao_user;
- protected $pageNavigation;
- protected $pageNavigation2;
- public function __construct()
- {
- parent::__construct();
- parent::include_css('app/resources/blue_modificado.css');
- parent::include_css('app/resources/custom-table.css');
- parent::include_css('app/resources/builder.css');
- // create form and table container
- $this->form_grupo = new BootstrapFormBuilder('form_grupo_usuario');
- $this->form_grupo->class = 'form_grupo_usuario';
- $this->form_grupo->id = 'form_grupo_usuario';
- $this->form = new TForm('frm_check');
- $this->style = 'width:100%';
- $this->form->class = 'form_grupo_usuario';
- $dados_grupo = new TLabel('Detalhes do Grupo');
- $dados_grupo->class ='lbl_titulo';
- $this->form_grupo->addContent( [$dados_grupo] );
- $lbl_nome = new TLabel(_t('Group`s name'));
- $lbl_descrcica_grupo = new TLabel(_t('Description'));
- $lbl_empresa = new TLabel(_t('Company'));
- $lbl_unidade_negocio = new TLabel(_t('Unit'));
- $id_grupo = new THidden('id_grupo');
- $nome_grupo = new TEntry('nome_grupo',new TRequiredValidator);
- $nome_grupo->placeholder = "Exemplo_empresa";
- $descricao_grupo = new TEntry('descricao_grupo');
- $nome_grupo->addValidation('nome do grupo', new TRequiredValidator); // required field
- $descricao_grupo->addValidation('descricao do grupo', new TRequiredValidator); // required field
- //$filter = new TCriteria;
- //$filter->add(new TFilter('id', '=',TSession::getValue('organizacion_id')));
- //combo 1(master)
- $organizacao_id = new TDBCombo('organizacao_id' ,'centinel','ViewOrganizacaoJuridica','id','nome','nome asc');
- $organizacao_id->setDefaultOption(false);
- $organizacao_id->setChangeAction( new TAction( array($this, 'onChangeActionFilial')) );
- $filter1 = new TCriteria;
- $filter1->add(new TFilter('id', '<','0'));
- //combo 2 (detail)
- $unidade_id = new TDBCombo('unidade_id','centinel','ViewOrganizacaoUnidade','id','name','name asc',$filter1);
- $unidade_id->setDefaultOption(false);
- $lbl_nome->class = 'lbl_text';
- $lbl_descrcica_grupo->class = 'lbl_text';
- $lbl_empresa->class = 'lbl_text';
- $lbl_unidade_negocio->class = 'lbl_text';
- $lbl_nome->setSize('100%');
- $lbl_descrcica_grupo->setSize('100%');
- $nome_grupo->setSize('100%');
- $descricao_grupo->setSize('100%');
- $organizacao_id->setSize('100%');
- $unidade_id->setSize('100%');
- $this->form_grupo->addFields([$lbl_nome]);
- $this->form_grupo->addFields([$nome_grupo]);
- $this->form_grupo->addFields([$lbl_descrcica_grupo]);
- $this->form_grupo->addFields([$descricao_grupo]);
- $this->form_grupo->addFields([$lbl_empresa]);
- $this->form_grupo->addFields([$organizacao_id]);
- $this->form_grupo->addFields([$lbl_unidade_negocio]);
- $this->form_grupo->addFields([$unidade_id]);
- $dados_grupo_configuracao = new TLabel('Configuração de menus e submenus');
- $dados_grupo_configuracao->class ='lbl_titulo';
- $this->form_grupo->addContent( [$dados_grupo_configuracao] );
- $this->form_grupo->addAction('Salvar',new TAction(array($this, 'onSave')),'fa:save blue');
- $this->form_grupo->addAction('Listar',new TAction(array('GrupoEmpresa','onReload')),'fa:table blue');
- // creates a DataGrid
- $this->datagrid = new TQuickGrid;
- $this->cartgrid = new TDataGrid;
- $this->datagrid_user = new TQuickGrid;
- $this->datagrid_alocacao_user = new TDataGrid;
- $this->datagrid->disableDefaultClick(); // important!
- $this->cartgrid->disableDefaultClick(); // important!
- $this->datagrid_user->disableDefaultClick(); // important!
- $this->datagrid_alocacao_user->disableDefaultClick(); // important!
- $this->datagrid->style = 'width:100%;';
- $this->cartgrid->style = 'width:100%;';
- $this->datagrid_user->style = 'width:100%;';
- $this->datagrid_alocacao_user->style = 'width:100%;';
- // creates the datagrid columns
- $this->datagrid->addQuickColumn(_t('Name'),'name','left');
- //cartgrid
- $id = new TDataGridColumn('id','ID','center','5%');
- $name = new TDataGridColumn('name',_t('Name'), 'left');
- $action_editar = new TDataGridColumn('action_editar', _t('Edit'),'center');
- $action_print = new TDataGridColumn('action_print', _t('Print'),'center');
- $action_visualizar = new TDataGridColumn('action_visualizar', _t('View'),'center');
- $action_aprovar = new TDataGridColumn('action_aprovar', _t('to approve'),'center');
- $system_menu = new TDataGridColumn('system_menu', 'menu','center');
- // creates the datagrid actions
- $order1 = new TAction(array($this, 'onReload'));
- $order2 = new TAction(array($this, 'onReload'));
- // define the ordering parameters
- $order1->setParameter('order', 'id');
- $order2->setParameter('order', 'name');
- // assign the ordering actions
- $id->setAction($order1);
- $name->setAction($order2);
- // add the columns to the datagrid
- $this->cartgrid->addColumn($name);
- $this->cartgrid->addColumn($action_editar);
- $this->cartgrid->addColumn($action_print);
- $this->cartgrid->addColumn($action_visualizar);
- $this->cartgrid->addColumn($action_aprovar);
- $this->cartgrid->addColumn($system_menu);
- $action = new TDataGridAction(array($this, 'onDelete'));
- $action->setLabel(_t('Delete'));
- $action->setImage('ico_delete.png');
- $action->setField('id');
- $this->cartgrid->addAction($action);
- // creates the datagrid columns
- $this->datagrid_user->addQuickColumn(_t('Name'),'name','left');
- // add the columns to the datagrid
- $this->datagrid_alocacao_user->addColumn($name);
- $action1 = new TDataGridAction(array($this, 'onDeleteUser'));
- $action1->setLabel(_t('Delete'));
- $action1->setImage('ico_delete.png');
- $action1->setField('id');
- $this->datagrid_alocacao_user->addAction($action1);
- // creates datagrid actions
- $this->datagrid->addQuickAction(_t('Select'),new TDataGridAction(array($this,'onSelect')), 'id','fa:plus-circle green','5%');
- $this->datagrid_user->addQuickAction(_t('Select').' '._t('user'),new TDataGridAction(array($this,'onSelectUser')), 'id','fa:plus-circle green','5%');
- // create the datagrid model
- $this->datagrid->createModel();
- $this->cartgrid->createModel();
- $this->datagrid_user->createModel();
- $this->datagrid_alocacao_user->createModel();
- // creates the page navigation datagrid
- $this->pageNavigation = new TPageNavigation;
- $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
- $this->pageNavigation->setWidth($this->datagrid->getWidth());
- // creates the page structure using a table
- $table1 = new TTable;
- $table1->style = 'width:100%;';
- $table1->addRow()->addCell($this->datagrid);
- $scroll1 = new TScroll;
- $scroll1->style = 'width:49.5%;float:left;height:300px;margin:0 0.5% 0 0;';
- $scroll1->add($table1);
- $div_paginacao = new TElement('div');
- $div_paginacao->id = 'div_paginacao';
- $div_paginacao->class = 'div_paginacao';
- $div_paginacao->add($this->pageNavigation) ;
- $scroll1->add($div_paginacao) ;
- $table2 = new TTable;
- $table2->style = 'width:100%;';
- $table2->addRow()->addCell($this->cartgrid);
- $scroll = new TScroll;
- $scroll->style = 'width:50%;height:300px;float:left;';
- $scroll->add($table2);
- // creates the page structure using a table
- $table3 = new TTable;
- $table3->style = 'width:100%;';
- $table3->addRow()->addCell($this->datagrid_user);
- $scroll2 = new TScroll;
- $scroll2->style = 'width:49.5%;float:left;height:300px;margin:0 0.5% 0 0;';
- $scroll2->add($table3);
- $table4 = new TTable;
- $table4->style = 'width:100%;';
- $table4->addRow()->addCell($this->datagrid_alocacao_user);
- $scroll3 = new TScroll;
- $scroll3->style = 'width:50%;height:300px;float:left;';
- $scroll3->add($table4);
- $hbox = new THBox;
- $hbox->add($scroll1)->style ='vertical-align:top;width:100%;';
- $hbox->add($scroll)->style ='vertical-align:top;width:100%;';
- // creates the page navigation
- $this->pageNavigation2 = new TPageNavigation;
- $this->pageNavigation2->setAction(new TAction(array($this, 'onReloadUser')));
- $this->pageNavigation2->setWidth($this->datagrid_user->getWidth());
- $div_paginacao1 = new TElement('div');
- $div_paginacao1->id = 'div_paginacao1';
- $div_paginacao1->class = 'div_paginacao';
- $div_paginacao1->add($this->pageNavigation2) ;
- $scroll2->add($div_paginacao1);
- $hbox1 = new THBox;
- $hbox1->add($scroll2)->style ='vertical-align:top;width:100%;';
- $hbox1->add($scroll3)->style ='vertical-align:top;width:100%;';
- $this->form_grupo->addFields([$hbox]);
- $titulo_alocacao_user = new TLabel('Alocação dos usuários');
- $titulo_alocacao_user->class ='lbl_titulo';
- $this->form_grupo->addContent( [$titulo_alocacao_user] );
- $this->form_grupo->addFields([$hbox1]);
- //wrap the page content using vertical box
- $vbox = new TVBox;
- $vbox->style = 'width:100%';
- $vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $vbox->add($this->form_grupo);
- parent::add($vbox);
- }
- /**
- * Put a programs inside the cart
- */
- public function onSelect($param)
- {
- // get the cart objects from session
- $cart_objects = TSession::getValue('cart_objects');
- TTransaction::open('permission');
- $programs = new SystemProgram($param['key']); // load the programs
- $cart_objects[$programs->id] = $programs; // add the programs inside the array
- TSession::setValue('cart_objects', $cart_objects); // put the array back to the session
- TTransaction::close();
- // reload datagrids
- $this->onReload( func_get_arg(0) );
- }
- public function onSelectUser($param)
- {
- // get the cart objects from session
- $alocacao_objects = TSession::getValue('alocacao_objects');
- TTransaction::open('permission');
- $user_object = new SystemUser($param['key']); // load the user
- $alocacao_objects[$user_object->id] = $user_object; // add the user inside the array
- TSession::setValue('alocacao_objects', $alocacao_objects);
- TTransaction::close();
- // reload datagrids
- $this->onReloadUser( func_get_arg(0) );
- }
- /**
- * Remove a programs from the cart
- */
- public function onDelete($param)
- {
- // get the cart objects from session
- $cart_objects = TSession::getValue('cart_objects');
- unset($cart_objects[$param['key']]); // remove the programs from the array
- TSession::setValue('cart_objects', $cart_objects); // put the array back to the session
- // reload datagrids
- $this->onReload( func_get_arg(0) );
- }
- public function onDeleteUser($param)
- {
- // get the cart objects from session
- $alocacao_objects = TSession::getValue('alocacao_objects');
- unset($alocacao_objects[$param['key']]); // remove the programs from the array
- TSession::setValue('alocacao_objects', $alocacao_objects); // put the array back to the session
- // reload datagrids
- $this->onReloadUser( func_get_arg(0) );
- }
- /**
- * method onReload()
- * Load the datagrid with the database objects
- */
- function onReload($param = NULL)
- {
- try
- {
- // open a transaction with database 'samples'
- TTransaction::open('permission');
- // creates a repository for Product
- $repository = new TRepository('SystemProgram');
- $limit = 5;
- // creates a criteria
- $criteria = new TCriteria;
- // default order
- if (empty($param['order']))
- {
- $param['order'] = 'id';
- $param['direction'] = 'asc';
- }
- $criteria->setProperties($param); // order, offset
- $criteria->setProperty('limit', $limit);
- $criteria->setProperty('order', 'controller');
- // load the objects according to criteria
- $objects = $repository->load($criteria);
- $this->datagrid->clear();
- if ($objects)
- {
- foreach ($objects as $object)
- {
- // add the object inside the datagrid
- $this->datagrid->addItem($object);
- }
- }
- //cartgrid
- $this->cartgrid->clear();
- $cart_objects = TSession::getValue('cart_objects');
- if ($cart_objects)
- {
- $cont = 1;
- foreach ($cart_objects as $object)
- {
- $uniqid = mt_rand(1000000, 9999999);
- $object->action_editar = new TCheckButton('check'.$uniqid);
- $object->action_editar->setIndexValue('on');
- $this->form->addField($object->action_editar); // important!
- $uniqid1 = mt_rand(1000000, 9999999);
- $object->action_print = new TCheckButton('check'.$uniqid1);
- $object->action_print->setIndexValue('on');
- $this->form->addField($object->action_print); // important!
- $uniqid2 = mt_rand(1000000, 9999999);
- $object->action_visualizar = new TCheckButton('check'.$uniqid2);
- $object->action_visualizar->setIndexValue('on');
- $this->form->addField($object->action_visualizar); // important
- $uniqid3 = mt_rand(1000000, 9999999);
- $object->action_aprovar = new TCheckButton('check'.$uniqid3);
- $object->action_aprovar->setIndexValue('on');
- $this->form->addField($object->action_aprovar); // important
- $uniqid4 = mt_rand(1000000, 9999999);
- $object->system_menu = new TDBCombo('system_menu'.$uniqid4, 'permission', 'SystemMenu', 'id', 'name');
- $this->form->addField($object->system_menu); // important
- $this->cartgrid->addItem($object);
- }
- }
- // reset the criteria for record count
- $criteria->resetProperties();
- $count= $repository->count($criteria);
- $this->pageNavigation->setCount($count); // count of records
- $this->pageNavigation->setProperties($param); // order, page
- $this->pageNavigation->setLimit($limit); // limit
- // close the transaction
- TTransaction::close();
- $this->loaded = true;
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- public function onReloadUser($param = NULL)
- {
- try
- {
- // open a transaction with database 'samples'
- TTransaction::open('permission');
- // creates a repository for SystemUser
- $repository1 = new TRepository('SystemUser');
- $limit1 = 5;
- // creates a criteria
- $criteria1 = new TCriteria;
- // default order
- if (empty($param['order']))
- {
- $param['order'] = 'id';
- $param['direction'] = 'asc';
- }
- $criteria1->setProperties($param); // order, offset
- $criteria1->setProperty('limit', $limit1);
- $criteria1->setProperty('order', 'name');
- // load the objects according to criteria
- $objects = $repository1->load($criteria1);
- $this->datagrid_user->clear();
- if ($objects)
- {
- foreach ($objects as $object)
- {
- // add the object inside the datagrid
- $this->datagrid_user->addItem($object);
- }
- }
- //datagrid_alocacao_user
- $this->datagrid_alocacao_user->clear();
- $alocacao_objects = TSession::getValue('alocacao_objects');
- if ($alocacao_objects)
- {
- foreach ($alocacao_objects as $object)
- {
- $this->datagrid_alocacao_user->addItem($object);
- }
- }
- // reset the criteria1 for record count
- $criteria1->resetProperties();
- $count1 = $repository1->count($criteria1);
- $this->pageNavigation2->setCount($count1); // count of records
- $this->pageNavigation2->setProperties($param); // order, page
- $this->pageNavigation2->setLimit($limit1); // limit
- // close the transaction
- TTransaction::close();
- $this->loaded1 = true;
- }
- catch (Exception $e)
- {
- // shows the exception error message
- new TMessage('error', '<b>Error</b> ' . $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- public function onSave($param)
- {
- try
- {
- $data = $this->form_grupo->getData(); // get form data
- $this->form_grupo->validate(); // validate form data
- // open a transaction with database 'permission'
- TTransaction::open('permission');
- // get the form data into an active record System_group
- $object = new SystemGroup;
- $object->name = $param['nome_grupo'];
- $object->description = $param['descricao_grupo'];
- $object->organization_id = $param['organizacao_id'];
- $object->unit_id = $param['unidade_id'];
- $object->active = 1;
- $object->store();
- $object->clearParts();
- $programs = TSession::getValue('cart_objects');
- if (!empty($programs))
- {
- foreach ($programs as $program)
- {
- $obj = $object->addSystemProgram( new SystemProgram( $program->id ) );
- //$object->system_edit = $check; //não estou conseguindo pegar este valores
- //$object->system_print = $check; //não estou conseguindo pegar este valores
- //$object->system_view = $check; //não estou conseguindo pegar este valores
- //print_r($programs).'<br/>';
- }
- }
- //adicionar usuários ao grupo
- $alocacao_objects = TSession::getValue('alocacao_objects');
- if (!empty($alocacao_objects))
- {
- foreach($alocacao_objects as $alocacao_object )
- {
- $object = new SystemUserGroup;
- $object->system_group_id = $obj;
- $object->system_user_id = $alocacao_object->id;
- $object->store();
- }
- }
- $data = new stdClass;
- $data->id_grupo = $object->id;
- TForm::sendData('form_grupo_usuario', $data);
- TTransaction::close(); // close the transaction
- new TMessage('info', _t('Record saved')); // shows the success message
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- /*
- // show form values inside a window
- $win = TWindow::create('test', 0.6, 0.8);
- $win->add( '<pre>'.str_replace("\n",'<br>', print_r(TSession::getValue('cart_objects'), true) ).'</pre><br/>'.$param['nome_grupo'].'<br>'.$param['descricao_grupo'].'<br/>'.$param['action_editar'] .'<br/>'.$param['action_print'].'<br/>'.$param['action_visualizar'] );
- $win->show();
- TForm::sendData('frm_gruop_usuario', $data);// keep form data
- TForm::sendData('frm_check', $data);// keep form data
- */
- }
- static function onChangeActionFilial($param)
- {
- try
- {
- TTransaction::open('centinel'); //base de dados
- if ($param['organizacao_id'])//se existe parâmetro da primeira combo(nome da primeira combo)
- {
- $criteria = TCriteria::create( ['organizacao_id' => $param['organizacao_id'] ] );
- //organizacao_id = parametro chave estrangeira da tabela master
- // formname,field(nome do campo),database , nome da model,key,value,ordercolumn = NULL,criteria, startEmpty = FALSE
- TDBCombo::reloadFromModel('form_grupo_usuario','unidade_id','centinel','ViewOrganizacaoUnidade','id','name', 'name',$criteria,TRUE);
- }
- else
- {
- TCombo::clearField('form_grupo_usuario', 'unidade_id'); //reload do formulario form_grupo_usuario na segunda combo "unidade_id"
- }
- TTransaction::close();
- }
- catch (Exception $e)
- {
- new TMessage('error', $e->getMessage());
- }
- }
- static function fireEvents( $object )
- {
- $obj = new stdClass;
- if(get_class($object) == 'stdClass')
- {
- if(isset($object->organizacao_id))
- {
- $obj->organizacao_id = $object->organizacao_id;
- }
- if(isset($object->unidade_id))
- {
- $obj->unidade_id = $object->unidade_id;
- }
- }
- else
- {
- if(isset($object->organizacao_id))
- {
- $obj->organizacao_id = $object->organizacao_id;
- }
- if(isset($object->unidade_id))
- {
- $obj->unidade_id = $object->unidade_id;
- }
- }
- TForm::sendData('form_grupo_usuario', $obj);
- }
- public function onClear($param)
- {
- $this->form->clear(TRUE);
- $this->form_grupo->clear(TRUE);
- }
- public function onEdit($param)
- {
- self::fireEvents($object);
- }
- /**
- * method show()
- * Shows the page
- */
- function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded)
- {
- $this->onReload( func_get_arg(0));
- $this->onReloadUser(func_get_arg(0));
- }
- parent::show();
- }
- }
- ?>
Os campos estão sendo registrados no formulário errado:
E evite usar uniqid para definir o nome dos campos, pois como esse valor muda a cada ação, não será possível capturar os dados do post na função onSave.
Nataniel,
Neste caso, como utilizo, pois quando usei pelo id, dava erro, "Você já adicionou um campo check ao formulário " .
Você pode usar o id, desde que mude o prefixo para não repetir o nome dos campos:
Nataniel,
Então, fiz como indicado porém continuo com o mesmo problema.
Veja a imagem no link : sgo.net.br/index.php?class=PublicView&PHPSESSID=feba6dc14b4c5dca
Tente:
Nataniel,
Não deu certo,
Undefined variable: object in /var/www/html/centinel/app/control/admin/SystemGroupBuilder.class.php on line 744, referer: localhost/centinel/index.php?class=SystemGroupList
Veja como ficou o código, talvez esteja fazendo errado.
Era pra acrescentar o if na função onReload, dentro do foreach:
A função show pode deixar como estava antes
Nataniel,
Funcionou, mais uma vez muito obrigado pelo apoio.