Ir para conteúdo

POWERED BY:

Marcelodiehl

Dúvida quanto onoffswitch-label

Recommended Posts

Boa tarde,

tenho um código php para envio de documentos para uma área do cliente e no admin onde eu realizo o upload dos documentos tem um input onoffswitch onde eu ativo ou desativo (Quando Ativo = "Mostrar na area dos clientes") mas quando envio um arquivo ele fica por default desativado, então tenho que ativar para que o cliente Visualize o documento. O que eu preciso é que este botão fique Ativado por default, mas não encontro no script onde mudo isso. Peço desculpas pela minha ignorancia em PHP, mas estou iniciando um curso esta semana, não sei muito ainda, mas já tenho este desafio. Alguém poderia me ajudar?

 

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<div class="modal fade" id="customer_file_share_file_with" data-total-contacts="<?php echo count($contacts); ?>" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title"><?php echo _l('share_file_with'); ?></h4>
        </div>
        <div class="modal-body">
            <?php echo form_hidden('file_id'); ?>
            <?php echo render_select('share_contacts_id[]',$contacts,array('id',array('firstname','lastname')),'customer_contacts',array(get_primary_contact_user_id($client->userid)),array('multiple'=>true,'data-actions-box'=>true),array(),'','',false); ?>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo _l('close'); ?></button>
            <button type="button" class="btn btn-info" onclick="do_share_file_contacts();"><?php echo _l('confirm'); ?></button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<h4 class="no-mtop bold"><?php echo _l('customer_attachments'); ?>
<br />
<small class="text-info"><?php echo _l('customer_files_info_message'); ?></small>
</h4>
<hr />
<?php if(isset($client)){ ?>
    <?php echo form_open_multipart(admin_url('clients/upload_attachment/'.$client->userid),array('class'=>'dropzone','id'=>'client-attachments-upload')); ?>
    <input type="file" name="file" multiple />
    <?php echo form_close(); ?>
    <div class="text-right mtop15">
        <button class="gpicker" data-on-pick="customerGoogleDriveSave">
            <i class="fa fa-google" aria-hidden="true"></i>
            <?php echo _l('choose_from_google_drive'); ?>
        </button>
        <div id="dropbox-chooser"></div>
    </div>
    <div class="attachments">
        <div class="mtop25">

            <table class="table dt-table scroll-responsive" data-order-col="2" data-order-type="desc">
                <thead>
                    <tr>
                        <th width="30%"><?php echo _l('customer_attachments_file'); ?></th>
                        <th><?php echo _l('customer_attachments_show_in_customers_area'); ?></th>
                        <th><?php echo _l('file_date_uploaded'); ?></th>
                        <th><?php echo _l('options'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($attachments as $type => $attachment){
                        $download_indicator = 'id';
                        $key_indicator = 'rel_id';
                        $upload_path = get_upload_path_by_type($type);
                        if($type == 'invoice' || $type == 'proposal' || $type == 'estimate' || $type == 'credit_note'){
                            $url = site_url() .'download/file/sales_attachment/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'contract'){
                            $url = site_url() .'download/file/contract/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'lead'){
                            $url = site_url() .'download/file/lead_attachment/';
                        } else if($type == 'task'){
                            $url = site_url() .'download/file/taskattachment/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'ticket'){
                            $url = site_url() .'download/file/ticket/';
                            $key_indicator = 'ticketid';
                        } else if($type == 'customer'){
                            $url = site_url() .'download/file/client/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'expense'){
                            $url = site_url() .'download/file/expense/';
                            $download_indicator = 'rel_id';
                        }
                        ?>
                        <?php foreach($attachment as $_att){
                            ?>
                            <tr id="tr_file_<?php echo $_att['id']; ?>">
                                <td>
                                   <?php
                                   $path = $upload_path . $_att[$key_indicator] . '/' . $_att['file_name'];
                                   $is_image = false;
                                   if(!isset($_att['external'])) {
                                    $attachment_url = $url . $_att[$download_indicator];
                                    $is_image = is_image($path);
                                    $img_url = site_url('download/preview_image?path='.protected_file_url_by_path($path,true).'&type='.$_att['filetype']);
                                    $lightBoxUrl = site_url('download/preview_image?path='.protected_file_url_by_path($path).'&type='.$_att['filetype']);
                                } else if(isset($_att['external']) && !empty($_att['external'])){

                                    if(!empty($_att['thumbnail_link']) && $_att['external'] == 'dropbox'){
                                        $is_image = true;
                                        $img_url = optimize_dropbox_thumbnail($_att['thumbnail_link']);
                                    }

                                    $attachment_url = $_att['external_link'];
                                }
                                if($is_image){
                                    echo '<div class="preview_image">';
                                }
                                ?>
                                <a href="<?php if($is_image){ echo isset($lightBoxUrl) ? $lightBoxUrl : $img_url; } else {echo $attachment_url; } ?>"<?php if($is_image){ ?> data-lightbox="customer-profile" <?php } ?> class="display-block mbot5">
                                    <?php if($is_image){ ?>
                                        <div class="table-image">
                                            <div class="text-center"><i class="fa fa-spinner fa-spin mtop30"></i></div>
                                            <img src="#" class="img-table-loading" data-orig="<?php echo $img_url; ?>">
                                        </div>
                                    <?php } else { ?>
                                     <i class="<?php echo get_mime_class($_att['filetype']); ?>"></i> <?php echo $_att['file_name']; ?>
                                 <?php } ?>
                             </a>
                             <?php if($is_image){ echo '</div>'; } ?>
                         </td>
                         <td>
                            <div class="onoffswitch"<?php if($type != 'customer'){?> data-toggle="tooltip" data-title="<?php echo _l('customer_attachments_show_notice'); ?>" <?php } ?>>
                                <input type="checkbox" <?php if($type != 'customer'){echo 'disabled';} ?> id="<?php echo $_att['id']; ?>" data-id="<?php echo $_att['id']; ?>" class="onoffswitch-checkbox customer_file" data-switch-url="<?php echo admin_url(); ?>misc/toggle_file_visibility" <?php if(isset($_att['visible_to_customer']) && $_att['visible_to_customer'] == 1){echo 'checked';} ?>>
                                <label class="onoffswitch-label" for="<?php echo $_att['id']; ?>"></label>
                            </div>
                            <?php if($type == 'customer' && $_att['visible_to_customer'] == 1){
                                $file_visibility_message = '';
                                $total_shares = total_rows(db_prefix().'shared_customer_files',array('file_id'=>$_att['id']));

                                if($total_shares == 0){
                                    $file_visibility_message = _l('file_share_visibility_notice');
                                } else {
                                    $share_contacts_id = get_customer_profile_file_sharing(array('file_id'=>$_att['id']));
                                    if(count($share_contacts_id) == 0){
                                        $file_visibility_message = _l('file_share_visibility_notice');
                                    }
                                }
                                echo '<span class="text-warning'.(empty($file_visibility_message) || total_rows(db_prefix().'contacts',array('userid'=>$client->userid)) == 0 ? ' hide': '').'">'.$file_visibility_message.'</span>';
                                if(isset($share_contacts_id) && count($share_contacts_id) > 0){
                                    $names = '';
                                    $contacts_selected = '';
                                    foreach($share_contacts_id as $file_share){
                                        $names.= get_contact_full_name($file_share['contact_id']) .', ';
                                        $contacts_selected .= $file_share['contact_id'].',';
                                    }
                                    if($contacts_selected != ''){
                                        $contacts_selected = substr($contacts_selected,0,-1);
                                        
                                        /**na linha abaixo em </a> ' . _l('share_file_with_show, trocando o _1 por 0 desabilita envio */
                                    }
                                    if($names != ''){
                                        echo '<a href="#" onclick="do_share_file_contacts(\''.$contacts_selected.'\','.$_att['id'].'); return false;"><i class="fa fa-pencil-square-o"></i></a> ' . _l('share_file_with_show',mb_substr($names, 0,-2));
                                    }
                                }
                            }
                            ?>
                        </td>
                        <td data-order="<?php echo $_att['dateadded']; ?>"><?php echo _dt($_att['dateadded']); ?></td>
                        <td>
                            <?php if(!isset($_att['external'])){ ?>
                                <button type="button" data-toggle="modal" data-file-name="<?php echo $_att['file_name']; ?>" data-filetype="<?php echo $_att['filetype']; ?>" data-path="<?php echo $path; ?>" data-target="#send_file" class="btn btn-info btn-icon"><i class="fa fa-envelope"></i></button>
                            <?php } else if(isset($_att['external']) && !empty($_att['external'])) {
                                echo '<a href="'.$_att['external_link'].'" class="btn btn-info btn-icon" target="_blank">'.($_att['external'] == 'dropbox' ? '<i class="fa fa-dropbox"></i>' : '<i class="fa fa-google"></i>').'</a>';
                            } ?>
                            <?php if($type == 'customer'){ ?>
                                <a href="<?php echo admin_url('clients/delete_attachment/'.$_att['rel_id'].'/'.$_att['id']); ?>"  class="btn btn-danger btn-icon _delete"><i class="fa fa-remove"></i></a>
                            <?php } ?>
                        </td>
                    <?php } ?>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>

</div>
<?php
include_once(APPPATH . 'views/admin/clients/modals/send_file_modal.php');

 

Compartilhar este post


Link para o post
Compartilhar em outros sites
17 horas atrás, Marcelodiehl disse:

Boa tarde,

tenho um código php para envio de documentos para uma área do cliente e no admin onde eu realizo o upload dos documentos tem um input onoffswitch onde eu ativo ou desativo (Quando Ativo = "Mostrar na area dos clientes") mas quando envio um arquivo ele fica por default desativado, então tenho que ativar para que o cliente Visualize o documento. O que eu preciso é que este botão fique Ativado por default, mas não encontro no script onde mudo isso. Peço desculpas pela minha ignorancia em PHP, mas estou iniciando um curso esta semana, não sei muito ainda, mas já tenho este desafio. Alguém poderia me ajudar?

 


<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<div class="modal fade" id="customer_file_share_file_with" data-total-contacts="<?php echo count($contacts); ?>" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title"><?php echo _l('share_file_with'); ?></h4>
        </div>
        <div class="modal-body">
            <?php echo form_hidden('file_id'); ?>
            <?php echo render_select('share_contacts_id[]',$contacts,array('id',array('firstname','lastname')),'customer_contacts',array(get_primary_contact_user_id($client->userid)),array('multiple'=>true,'data-actions-box'=>true),array(),'','',false); ?>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo _l('close'); ?></button>
            <button type="button" class="btn btn-info" onclick="do_share_file_contacts();"><?php echo _l('confirm'); ?></button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<h4 class="no-mtop bold"><?php echo _l('customer_attachments'); ?>
<br />
<small class="text-info"><?php echo _l('customer_files_info_message'); ?></small>
</h4>
<hr />
<?php if(isset($client)){ ?>
    <?php echo form_open_multipart(admin_url('clients/upload_attachment/'.$client->userid),array('class'=>'dropzone','id'=>'client-attachments-upload')); ?>
    <input type="file" name="file" multiple />
    <?php echo form_close(); ?>
    <div class="text-right mtop15">
        <button class="gpicker" data-on-pick="customerGoogleDriveSave">
            <i class="fa fa-google" aria-hidden="true"></i>
            <?php echo _l('choose_from_google_drive'); ?>
        </button>
        <div id="dropbox-chooser"></div>
    </div>
    <div class="attachments">
        <div class="mtop25">

            <table class="table dt-table scroll-responsive" data-order-col="2" data-order-type="desc">
                <thead>
                    <tr>
                        <th width="30%"><?php echo _l('customer_attachments_file'); ?></th>
                        <th><?php echo _l('customer_attachments_show_in_customers_area'); ?></th>
                        <th><?php echo _l('file_date_uploaded'); ?></th>
                        <th><?php echo _l('options'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($attachments as $type => $attachment){
                        $download_indicator = 'id';
                        $key_indicator = 'rel_id';
                        $upload_path = get_upload_path_by_type($type);
                        if($type == 'invoice' || $type == 'proposal' || $type == 'estimate' || $type == 'credit_note'){
                            $url = site_url() .'download/file/sales_attachment/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'contract'){
                            $url = site_url() .'download/file/contract/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'lead'){
                            $url = site_url() .'download/file/lead_attachment/';
                        } else if($type == 'task'){
                            $url = site_url() .'download/file/taskattachment/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'ticket'){
                            $url = site_url() .'download/file/ticket/';
                            $key_indicator = 'ticketid';
                        } else if($type == 'customer'){
                            $url = site_url() .'download/file/client/';
                            $download_indicator = 'attachment_key';
                        } else if($type == 'expense'){
                            $url = site_url() .'download/file/expense/';
                            $download_indicator = 'rel_id';
                        }
                        ?>
                        <?php foreach($attachment as $_att){
                            ?>
                            <tr id="tr_file_<?php echo $_att['id']; ?>">
                                <td>
                                   <?php
                                   $path = $upload_path . $_att[$key_indicator] . '/' . $_att['file_name'];
                                   $is_image = false;
                                   if(!isset($_att['external'])) {
                                    $attachment_url = $url . $_att[$download_indicator];
                                    $is_image = is_image($path);
                                    $img_url = site_url('download/preview_image?path='.protected_file_url_by_path($path,true).'&type='.$_att['filetype']);
                                    $lightBoxUrl = site_url('download/preview_image?path='.protected_file_url_by_path($path).'&type='.$_att['filetype']);
                                } else if(isset($_att['external']) && !empty($_att['external'])){

                                    if(!empty($_att['thumbnail_link']) && $_att['external'] == 'dropbox'){
                                        $is_image = true;
                                        $img_url = optimize_dropbox_thumbnail($_att['thumbnail_link']);
                                    }

                                    $attachment_url = $_att['external_link'];
                                }
                                if($is_image){
                                    echo '<div class="preview_image">';
                                }
                                ?>
                                <a href="<?php if($is_image){ echo isset($lightBoxUrl) ? $lightBoxUrl : $img_url; } else {echo $attachment_url; } ?>"<?php if($is_image){ ?> data-lightbox="customer-profile" <?php } ?> class="display-block mbot5">
                                    <?php if($is_image){ ?>
                                        <div class="table-image">
                                            <div class="text-center"><i class="fa fa-spinner fa-spin mtop30"></i></div>
                                            <img src="#" class="img-table-loading" data-orig="<?php echo $img_url; ?>">
                                        </div>
                                    <?php } else { ?>
                                     <i class="<?php echo get_mime_class($_att['filetype']); ?>"></i> <?php echo $_att['file_name']; ?>
                                 <?php } ?>
                             </a>
                             <?php if($is_image){ echo '</div>'; } ?>
                         </td>
                         <td>
                            <div class="onoffswitch"<?php if($type != 'customer'){?> data-toggle="tooltip" data-title="<?php echo _l('customer_attachments_show_notice'); ?>" <?php } ?>>
                                <input type="checkbox" <?php if($type != 'customer'){echo 'disabled';} ?> id="<?php echo $_att['id']; ?>" data-id="<?php echo $_att['id']; ?>" class="onoffswitch-checkbox customer_file" data-switch-url="<?php echo admin_url(); ?>misc/toggle_file_visibility" <?php if(isset($_att['visible_to_customer']) && $_att['visible_to_customer'] == 1){echo 'checked';} ?>>
                                <label class="onoffswitch-label" for="<?php echo $_att['id']; ?>"></label>
                            </div>
                            <?php if($type == 'customer' && $_att['visible_to_customer'] == 1){
                                $file_visibility_message = '';
                                $total_shares = total_rows(db_prefix().'shared_customer_files',array('file_id'=>$_att['id']));

                                if($total_shares == 0){
                                    $file_visibility_message = _l('file_share_visibility_notice');
                                } else {
                                    $share_contacts_id = get_customer_profile_file_sharing(array('file_id'=>$_att['id']));
                                    if(count($share_contacts_id) == 0){
                                        $file_visibility_message = _l('file_share_visibility_notice');
                                    }
                                }
                                echo '<span class="text-warning'.(empty($file_visibility_message) || total_rows(db_prefix().'contacts',array('userid'=>$client->userid)) == 0 ? ' hide': '').'">'.$file_visibility_message.'</span>';
                                if(isset($share_contacts_id) && count($share_contacts_id) > 0){
                                    $names = '';
                                    $contacts_selected = '';
                                    foreach($share_contacts_id as $file_share){
                                        $names.= get_contact_full_name($file_share['contact_id']) .', ';
                                        $contacts_selected .= $file_share['contact_id'].',';
                                    }
                                    if($contacts_selected != ''){
                                        $contacts_selected = substr($contacts_selected,0,-1);
                                        
                                        /**na linha abaixo em </a> ' . _l('share_file_with_show, trocando o _1 por 0 desabilita envio */
                                    }
                                    if($names != ''){
                                        echo '<a href="#" onclick="do_share_file_contacts(\''.$contacts_selected.'\','.$_att['id'].'); return false;"><i class="fa fa-pencil-square-o"></i></a> ' . _l('share_file_with_show',mb_substr($names, 0,-2));
                                    }
                                }
                            }
                            ?>
                        </td>
                        <td data-order="<?php echo $_att['dateadded']; ?>"><?php echo _dt($_att['dateadded']); ?></td>
                        <td>
                            <?php if(!isset($_att['external'])){ ?>
                                <button type="button" data-toggle="modal" data-file-name="<?php echo $_att['file_name']; ?>" data-filetype="<?php echo $_att['filetype']; ?>" data-path="<?php echo $path; ?>" data-target="#send_file" class="btn btn-info btn-icon"><i class="fa fa-envelope"></i></button>
                            <?php } else if(isset($_att['external']) && !empty($_att['external'])) {
                                echo '<a href="'.$_att['external_link'].'" class="btn btn-info btn-icon" target="_blank">'.($_att['external'] == 'dropbox' ? '<i class="fa fa-dropbox"></i>' : '<i class="fa fa-google"></i>').'</a>';
                            } ?>
                            <?php if($type == 'customer'){ ?>
                                <a href="<?php echo admin_url('clients/delete_attachment/'.$_att['rel_id'].'/'.$_att['id']); ?>"  class="btn btn-danger btn-icon _delete"><i class="fa fa-remove"></i></a>
                            <?php } ?>
                        </td>
                    <?php } ?>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>

</div>
<?php
include_once(APPPATH . 'views/admin/clients/modals/send_file_modal.php');

 

Função

 

 public function toggle_file_visibility($id)
    {
        $this->db->where('id', $id);
        $row = $this->db->get(db_prefix() . 'files')->row();
        if ($row->visible_to_customer == 1) {
            $v = 0;
        } else {
            $v = 1;
        }

        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'files', [
            'visible_to_customer' => $v,
        ]);
        echo $v;
    }
 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Função

 

public function files()
    {
        $files_where = 'visible_to_customer = 1 AND id IN (SELECT file_id FROM ' . db_prefix() . 'shared_customer_files WHERE contact_id =' . get_contact_user_id() . ')';

        $files_where = hooks()->apply_filters('customers_area_files_where', $files_where);

        $files = $this->clients_model->get_customer_files(get_client_user_id(), $files_where);

        $data['files'] = $files;
        $data['title'] = _l('customer_attachments');
        $this->data($data);
        $this->view('files');
        $this->layout();
    }

Compartilhar este post


Link para o post
Compartilhar em outros sites

Há quatro possibilidades de deixar ativado automaticamente.

1 - Se tem acesso ao banco, ja deixa ativado como default
2 - Verique o codigo onde recebe os dados e seta para ativo.

3 - Passe um campo no formulário do tipo hidden com o valor true
4 - Passe um campo do tipo ckeckbox/select,  com o valor true

Independente de qual forma passar, vai ter que descobrir como esta o nome no banco.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por belann
      Olá!
       
      Estou usando o nextjs versão 15.2.3 e criei uma navbar que quando é carregado o programa aparece com a home, mas na hora de clicar na página produtos desaparece a navbar.
      A navbar esta sendo chamada no layout.tsx estou usando typescript
      e fica dessa forma
      <div>           <Navbar/>             <main>{children}</main>             </div>  
    • Por luiz monteiro
      Olá, tudo bem?
       
      Estou melhorando meu conhecimento em php e mysql e, me deparei com o seguinte. A tabela da base de dados tem um campo do tipo varchar(8) o qual armazena números. Eu não posso alterar o tipo desse campo. O que preciso é fazer um select para retornar o números que contenham zeros a direita ou a esquerda.
      O que tentei até agora
       
      Ex1
      $busca = $conexao->prepare("select campo form tabela where (campo = :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form']);
       
      Se a direita da string $_REQUEST['campo_form'] termina ou inicia com zero ou zeros, a busca retorna vazio.
      Inseri dados numéricos, da seguinte maneira para testar: 01234567;  12345670: 12345678: 12340000... entre outros nessa coluna. Todos os valores que não terminam ou não iniciam com zero ou zeros, o select funciona.
       
       
      Ex2
      $busca = $conexao->prepare("select campo form tabela where (campo = 0340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex3
      $busca = $conexao->prepare("select campo form tabela where (campo = '02340001' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex4
      $busca = $conexao->prepare("select campo form tabela where (campo like 2340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex5
      $busca = $conexao->prepare("select campo form tabela where (campo like '12340000') ");
      Esse número está cadastrado, mas não retorna.
       
      Ex6
      $busca = $conexao->prepare("select campo form tabela where (campo like '"12340000"' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex7
      $busca = $conexao->prepare("select campo form tabela where (campo like :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form'])
      Não retorna dados.
       
      O  $_REQUEST['campo_form'] é envio via AJAX de um formulário. 
      Usei o gettype para verificar o post, e ele retorna string.
      Fiz uma busca com número 12345678 para verificar o que o select retorna, e também retrona como string.
       
      Esse tipo de varchar foi usado porque os números que serão gravados nesse campo,  terão zeros a direita ou na esquerda. Os tipos number do mysql não gravam zeros, então estou usando esse. O problema é a busca.
      Agradeço desde já.
       
       
    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.