Como condicionar um botão à seleção de um combo box Boa tarde, estou precisando da seguinte ajuda: Preciso condicionar um botão à seleção do combo box, exemplo: ao selecionar uma das opções existentes no combo box o botão aparecerá, caso contrário ficará escondido. Preciso pegar o id da opção e criar uma estrutura de decisão para esconder o botão....
MS
Como condicionar um botão à seleção de um combo box  
Boa tarde, estou precisando da seguinte ajuda:

Preciso condicionar um botão à seleção do combo box, exemplo:
ao selecionar uma das opções existentes no combo box o botão aparecerá, caso contrário ficará escondido.
Preciso pegar o id da opção e criar uma estrutura de decisão para esconder o botão.

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (6)


NR

Que classe de formulário você está utilizando?

Se deixar o botão desabilitado resolve, veja o exemplo abaixo:
adianti.com.br/framework_files/tutor/index.php?class=FormConditional
MS

Estou usando o TForm e dentro uma TTable, o combo ta como TDBCombo e o botão padrão com TButton
NR

A função TQuickForm::hideField($nome_form,$nome_widget) esconde o container pai que contenha a classe tformrow. Você pode fazer o seguinte:
<?php$combo = new TCombo('combo');$combo->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo$button = TButton::create('save',[$this,'onSave'],'Salvar','fa:save');$row = $table->addRow();$row->class = 'tformrow'; // importante, pois a hideField vai procurar por essa classe para ocultar$row->addCell($button);// function changeComboif (condicao)   TQuickForm::hideField('nome_form','nome_botao');else   TQuickForm::showField('nome_form','nome_botao');?>
MS

Não está executando, da uma janela de erro no aplicação

<?php        $id_sala        = new TDBCombo('id_sala', 'permission', 'Sala', 'id_sala', 'sg_sala');        $id_sala->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo        // create an print button (imprimir autorizacao de saida de automovel)        $print_button=new TButton('print');        $print_button->setAction(new TAction(array($this, 'onPrint')), 'Imprimir Autorização','fa:print');                $row = $table->addRow();        $row->class = 'print'; // importante, pois a hideField vai procurar por essa classe para ocultar        $row->addCell($print_button);                /*function changeCombo{            if ($id_sala > 4){                TQuickForm::hideField('$id_sala','$print_button');            }            else{                TQuickForm::showField('$id_sala','$print_button');            }        }*/?>
MS

A função não está marcada como acima, apenas mandei uma cópia errada

Segue código inteiro:
<?php/** * CalendarEventForm */class CalendarEventForm extends TWindow{    protected $form; // form        /**     * Class constructor     * Creates the page and the registration form     */    public function __construct()    {        parent::__construct();        parent::setSize(640, null);        parent::setTitle('Calendário  [Evento]');                // creates the form        $this->form = new TForm('form_event');        $this->form->class = 'tform'; // CSS class        $this->form->style = 'width: 600px';                // add a table inside form        $table = new TTable;        $table-> width = '100%';        $this->form->add($table);                // add a row for the form title        $row = $table->addRow();        $row->class = 'tformtitle'; // CSS class        $row->addCell( new TLabel('Evento') )->colspan = 2;                $hours = array();        $minutes = array();        for ($n=0; $n<24; $n++)        {            $hours[$n] = str_pad($n, 2, '0', STR_PAD_LEFT);        }                for ($n=0; $n<=55; $n+=5)        {            $minutes[$n] = str_pad($n, 2, '0', STR_PAD_LEFT);        }                // create the form fields        $view           = new THidden('view');        $id             = new TEntry('id');        $id_sala        = new TDBCombo('id_sala', 'permission', 'Sala', 'id_sala', 'sg_sala');        $id_sala->setChangeAction(new TAction(array($this,'changeCombo'))); // acao ao alterar valor da combo        $color          = new TColor('color');        $start_date     = new TDate('start_date');        $start_hour     = new TCombo('start_hour');        $start_minute   = new TCombo('start_minute');        $end_date       = new TDate('end_date');        $end_hour       = new TCombo('end_hour');        $end_minute     = new TCombo('end_minute');        $title          = new TEntry('title');        $description    = new TText('description');        $participantes  = new TDBMultiSearch('participantes', 'permission', 'SystemUser', 'id', 'name');        $login          = new TEntry('login');        $color->setValue('#3a87ad');                $start_hour->addItems($hours);        $start_minute->addItems($minutes);        $end_hour->addItems($hours);        $end_minute->addItems($minutes);        $id_sala->setDefaultOption(FALSE);        $participantes->setMinLength(3);        $login->setValue(TSession::getValue('login'));        $login->setEditable(FALSE);        $id->setEditable(FALSE);                // define the sizes        $id->setSize(60);        $id_sala->setSize(100);        $color->setSize(100);        $start_date->setSize(100);        $end_date->setSize(100);        $start_hour->setSize(50);        $end_hour->setSize(50);        $start_minute->setSize(50);        $end_minute->setSize(50);        $title->setSize(400);        $description->setSize(400, 50);        $participantes->setSize(400, 50);        $start_hour->setChangeAction(new TAction(array($this, 'onChangeStartHour')));        $end_hour->setChangeAction(new TAction(array($this, 'onChangeEndHour')));        $start_date->setExitAction(new TAction(array($this, 'onChangeStartDate')));        $end_date->setExitAction(new TAction(array($this, 'onChangeEndDate')));        // add one row for each form field        $table->addRowSet( $view );        $table->addRowSet( new TLabel('#:'), [$id , new TLabel('Proprietário:'), $login]);        $table->addRowSet( new TLabel('Sala/Carro/Viagem:'), $id_sala );       // $table->addRowSet( new TLabel('Color:'), $color );        $table->addRowSet( new TLabel('Início:'), array($start_date, $start_hour, ':', $start_minute) );        $table->addRowSet( new TLabel('Término:'), array($end_date, $end_hour, ':', $end_minute));        $table->addRowSet( new TLabel('Título:'), $title );        $table->addRowSet( new TLabel('Descrição:'), $description );        $table->addRowSet( new TLabel('Participantes:'), $participantes );        // create an action button (save)        $save_button=new TButton('save');        $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));        $save_button->setImage('fa:save green');         // create an new button (edit with no parameters)        $new_button=new TButton('new');        $new_button->setAction(new TAction(array($this, 'onEdit')), 'Limpar');        $new_button->setImage('fa:eraser blue');        // create an del button (edit with no parameters)        $del_button=new TButton('del');        $del_button->setAction(new TAction(array($this, 'onDelete')), _t('Delete'));        $del_button->setImage('fa:trash-o red');        // create an print button (imprimir autorizacao de saida de automovel)        $print_button=new TButton('print');        $print_button->setAction(new TAction(array($this, 'onPrint')), 'Imprimir Autorização','fa:print');                $row = $table->addRow();        $row->class = 'print'; // importante, pois a hideField vai procurar por essa classe para ocultar        $row->addCell($print_button);                function changeCombo{            if ($id_sala('id_sala') > 4){                TQuickForm::hideField('$id_sala','$print_button');            }            else{                TQuickForm::showField('$id_sala','$print_button');            }        }        $this->form->setFields(array($id, $view, $login, $participantes, $color,$id_sala, $title, $description, $start_date, $start_hour, $start_minute, $end_date, $end_hour, $end_minute, $save_button,$new_button,$del_button, $print_button));                $buttons_box = new THBox;        $buttons_box->add($save_button);        $buttons_box->add($new_button);        $buttons_box->add($del_button);        $buttons_box->add($print_button);                // add a row for the form action        $row = $table->addRow();        $row->class = 'tformaction'; // CSS class        $row->addCell($buttons_box)->colspan = 2;                parent::add($this->form);    }    /**     * Executed when user leaves start hour field     */    public static function onChangeStartHour($param=NULL)    {        $obj = new stdClass;        if (empty($param['start_minute']))        {            $obj->start_minute = '0';            TForm::sendData('form_event', $obj);        }                if (empty($param['end_hour']) AND empty($param['end_minute']))        {            $obj->end_hour = $param['start_hour'] +1;            $obj->end_minute = '0';            TForm::sendData('form_event', $obj);        }    }        /**     * Executed when user leaves end hour field     */    public static function onChangeEndHour($param=NULL)    {        if (empty($param['end_minute']))        {            $obj = new stdClass;            $obj->end_minute = '0';            TForm::sendData('form_event', $obj);        }    }        /**     * Executed when user leaves start date field     */    public static function onChangeStartDate($param=NULL)    {        if (empty($param['end_date']) AND !empty($param['start_date']))        {            $obj = new stdClass;            $obj->end_date = $param['start_date'];            TForm::sendData('form_event', $obj);        }    }        /**     * Executed when user leaves end date field     */    public static function onChangeEndDate($param=NULL)    {        if (empty($param['end_hour']) AND empty($param['end_minute']) AND !empty($param['start_hour']))        {            $obj = new stdClass;            $obj->end_hour = min($param['start_hour'],22) +1;            $obj->end_minute = '0';            TForm::sendData('form_event', $obj);        }    }        /**     * method onSave()     * Executed whenever the user clicks at the save button     */    public function onSave()    {        try        {                        // open a transaction            TTransaction::open('permission');            $this->form->validate(); // form validation            // get the form data into an active record Entry            $data = $this->form->getData();            if (empty($data->id))             {                $conn = TTransaction::get();                $status = 'agendada';                $id_sala  = $data->id_sala;                $dh_start = $data->start_date . ' ' . str_pad($data->start_hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->start_minute, 2, '0', STR_PAD_LEFT) . ':30';                $mssql = "select id from calendar_event where id_sala = '{$id_sala}' and ( '{$dh_start}' between start_time and end_time )";                                      // executa a instrução SQL                $result = $conn->query($mssql);                $resp = $result->fetchObject();                          }                        if  (isset($resp) and ($resp))             {                 new TMessage('info', 'Não foi possível gravar, já tem reunião nesse horário');            }            else            {                 $object = new CalendarEvent;                $status = ($status <> '')? $status : 'alterada';                                // $object->color       = $data->color;                $object->id          = $data->id;                $object->title       = $data->title;                $object->description = $data->description;                $object->start_time  = $data->start_date . ' ' . str_pad($data->start_hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->start_minute, 2, '0', STR_PAD_LEFT) . ':00';                $object->end_time    = $data->end_date   . ' ' . str_pad($data->end_hour  , 2, '0', STR_PAD_LEFT) . ':' . str_pad($data->end_minute  , 2, '0', STR_PAD_LEFT) . ':00';                $object->login       = (empty($data->login)) ? TSession::getValue('login') : $data->login  ;                  $object->id_sala     = $data->id_sala;                                                $key_participantes = array_keys($data->participantes);                    // gravar os participantes em um único campo                //------------------------------------------------------------------                 $membros = '';                             if ($key_participantes)                {                      $membros = implode(';', $key_participantes);                }                $object->participantes = $membros;                                                             $object->store(); // stores the object                                $data->id = $object->id;                $this->form->setData($data); // keep form data                                                                $posAction = new TAction(array('FullCalendarDatabaseView', 'onReload'));                $posAction->setParameter('view', $data->view);                $posAction->setParameter('date', $data->start_date);                                // shows the success message                // new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'), $posAction);                 $param['view'] = $data->view;                  $param['date'] = $data->start_date;                                   AdiantiCoreApplication::loadPage('FullCalendarDatabaseView', 'onReload', $param);                                $param   = [];                $pessoas = [];                                foreach($key_participantes as $id)                {                    $user =  SystemUser::find($id);                    if ($user)                    {                            $pessoas[] = [$user->email,$user->name];                       }                 }                $sala = new Sala($data->id_sala);                                $param['dt_ini'] = $object->start_time;                $param['dt_fim'] = $object->end_time;                                $param['titulo']   = $data->title;                 $param['descricao']= $data->description;                $param['pessoas']  = $pessoas;                $param['status']   = $status;                $param['sala']     = $sala->sg_sala;                TTransaction::close(); // close the transaction               $action = new TAction(['FullCalendarDatabaseView', 'EnviarEmail']);               $action->setParameters($param);                  new TQuestion('Registro Salvo!!!, deseja enviar email?', $action);            }            TTransaction::close(); // close the transaction        }        catch (Exception $e) // in case of exception        {            // shows the exception error message            new TMessage('error', $e->getMessage());                        $this->form->setData( $this->form->getData() ); // keep form data                        // undo all pending operations            TTransaction::rollback();        }    }        /**     * method onEdit()     * Executed whenever the user clicks at the edit button da datagrid     */    public function onEdit($param)    {        try        {            $data = new stdClass;            if (isset($param['key']))            {                // get the parameter $key                $key=$param['key'];                                // open a transaction with database                TTransaction::open('permission');                                // instantiates object CalendarEvent                $object = new CalendarEvent($key);                                             // $data = new stdClass;                $data->id = $object->id;                $data->color = $object->color;                $data->id_sala = $object->id_sala;                $data->title = $object->title;                $data->description = $object->description;                $data->start_date = substr($object->start_time,0,10);                $data->start_hour = substr($object->start_time,11,2);                $data->start_minute = substr($object->start_time,14,2);                $data->end_date = substr($object->end_time,0,10);                $data->end_hour = substr($object->end_time,11,2);                $data->end_minute = substr($object->end_time,14,2);                $data->view = $param['view'];                $data->login = $object->login;                //Carregar os participantes                $vetor = explode(';',$object->participantes);                 $participantes = [];                                 foreach($vetor as $id)                {                   $user =  SystemUser::find($id);                   if ($user)                   {                         $participantes[$user->id] = $user->name;                      }                 }                            $data->participantes = $participantes;                                // fill the form with the active record data                $this->form->setData($data);                if ($object->login <> TSession::getValue('login'))                {                    TButton::disableField('form_event', 'save');                    TButton::disableField('form_event', 'new');                    TButton::disableField('form_event', 'del');                }                                                // close the transaction                TTransaction::close();                            }            else            {                $this->form->clear();                $data->login = TSession::getValue('login');                $this->form->setData($data);            }        }        catch (Exception $e) // in case of exception        {            // shows the exception error message            new TMessage('error', $e->getMessage());                        // undo all pending operations            TTransaction::rollback();        }    }        /**     * Delete event     */    public static function onDelete($param)    {        // define the delete action        $action = new TAction(array('CalendarEventForm', 'Delete'));        $action->setParameters($param); // pass the key parameter ahead                // shows a dialog to the user        new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);    }        /**     * Delete a record     */    public static function Delete($param)    {        try        {            var_dump($param);                        // get the parameter $key            $key = $param['id'];            // open a transaction with database            TTransaction::open('permission');                        // instantiates object            $object = new CalendarEvent($key, FALSE);                        // deletes the object from the database            $object->delete();                        // close the transaction            TTransaction::close();                        $posAction = new TAction(array('FullCalendarDatabaseView', 'onReload'));            $posAction->setParameter('view', $param['view']);            $posAction->setParameter('date', $param['start_date']);                        // shows the success message                        new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'), $posAction);        }        catch (Exception $e) // in case of exception        {            // shows the exception error message            new TMessage('error', $e->getMessage());            // undo all pending operations            TTransaction::rollback();        }    }        /**     * Fill form from the user selected time     */    public function onStartEdit($param)    {        $this->form->clear();        $data = new stdClass;        $data->view = $param['view']; // calendar view        $data->color = '#3a87ad';                if ($param['date'])        {            if (strlen($param['date']) == 10)            {                $data->start_date = $param['date'];                $data->end_date = $param['date'];            }            if (strlen($param['date']) == 19)            {                $data->start_date   = substr($param['date'],0,10);                $data->start_hour   = substr($param['date'],11,2);                $data->start_minute = substr($param['date'],14,2);                                $data->end_date   = substr($param['date'],0,10);                $data->end_hour   = substr($param['date'],11,2) +1;                $data->end_minute = substr($param['date'],14,2);            }            $this->form->setData( $data );        }    }        /**     * Update event. Result of the drag and drop or resize.     */    public static function onUpdateEvent($param)    {        try        {            if (isset($param['id']))            {                // get the parameter $key                $key=$param['id'];                                // open a transaction with database                TTransaction::open('permission');                                // instantiates object CalendarEvent                $object = new CalendarEvent($key);                $object->start_time = str_replace('T', ' ', $param['start_time']);                $object->end_time   = str_replace('T', ' ', $param['end_time']);                $object->store();                                                // close the transaction                TTransaction::close();            }        }        catch (Exception $e) // in case of exception        {            new TMessage('error', '<b>Error</b> ' . $e->getMessage());            TTransaction::rollback();        }    }    public static function onPrint($param)    {        TScript::create('window.open("https://drive.google.com/file/d/15XypKw8KXA58yYwZTB3qvcaWxL9Tf31X/view?usp=sharing","_blank")');     }}?>
NR

Declare a função changeCombo fora do construtor. Veja o exemplo:
adianti.com.br/framework_files/tutor/index.php?class=FormInteraction