Save form data without obligation to update image

Asked

Viewed 118 times

1

I have a registration form and this form has a profile image of the registered user.

The insert and update image are working perfectly.

The problem is when I update any data other than the image, the system does not save, returning image upload error.

The form is not accepting the empty input file and wants to update the image anyway.

What do I want: Edit and Save CPF or NAME. Keep IMAGE that is already registered without obligation to change it

HTML code part - PHP - CSS - JAVASCRIPT

function preview(fileInput) {
    var files = fileInput.files;
    for (var i = 0; i < files.length; i++) {           
        var file = files[i];
        var imageType = /image.*/;     
        if (!file.type.match(imageType)) {
            continue;
        }           
        var img=document.getElementById("avatar");            
        img.file = file;    
        var reader = new FileReader();
        reader.onload = (function(aImg) { 
            return function(e) { 
                aImg.src = e.target.result; 
            }; 
        })(img);
        reader.readAsDataURL(file);
    }    
}
#avatar {
    width: 180px;
    height: 180px;
    background-position: center center;
    background-size: cover;	
	border-radius: 0;
	-moz-border-radius: 0px;
	-webkit-border-radius: 0px;
    -webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
    display: inline-block;
}
<div class="collapse in accordion-body" id="collapseGOne"><!--Dados Pessoais-->
<div class="widget-content ">
    <table>
        <tbody>
        <tr>
        <td style="width: 14%">
            <?php if (!empty($result->url_foto)) { ?>
                <img id="avatar" src="<?php echo $result->url_foto; ?>" >
            <?php }
            else
            {
                return;
            }
            ?>
            </div>
        </td>
<td>
    <div class="span12" style="padding: 1%">
        <div class="span4">
        <?php echo form_hidden('idColaboradores',$result->idColaboradores) ?>
            <label for="nome">Nome<span class="required">*</span></label>
            <input id="nome" class="span12" type="text" name="nome" value="<?php echo $result->nome; ?>"  />
        </div>
        <div class="span2">
            <label for="sexo">Sexo<span class="required">*</span></label>
            <select name="sexo" id="sexo" class="span12" value="">
                <option <?php if($result->sexo == 'Masculino'){echo 'selected';} ?> value="Masculino">Masculino</option>
                 <option <?php if($result->sexo == 'Feminino'){echo 'selected';} ?> value="Feminino">Feminino</option>
            </select>
        </div>
    </div>
    <div class="span12" style="padding: 1%; margin-left: 0">
        <div class="span2">
            <label for="cpf">CPF<span class="required">*</span></label>
            <input id="cpf" class="span12 cpf" type="text" name="cpf" placeholder="000.000.000-00" value="<?php echo $result->cpf; ?>"  />
        </div>
        <div class="span2">
            <label for="rg">RG<span class="required">*</span></label>
            <input id="rg" class="span12" type="text" name="rg" value="<?php echo $result->rg; ?>"  />
        </div>
        <div class="span2">
            <label for="data_nascimento">Data Nascimento<span class="required">*</span></label>
             <input id="data_nascimento" class="span12" type="date" name="data_nascimento" value="<?php echo $result->data_nascimento; ?>"  />
        </div>
    </div>
</td>
         </tr>
        </tbody>
    </table>
</div>

<div class=""><!--input Foto-->
    <label for="" class="control-label"><span class="required">Foto*</span></label>
    <div class="controls">
        <input type="file" onchange="preview(this)" name="userfile" /> (.png, .jpg, .jpeg)
    </div>
</div><!--input Foto-->
    
</div><!--Dados Pessoais-->

Part of Controller Code - PHP

function editar() {

        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'eColaborador')){
           $this->session->set_flashdata('error','Você não tem permissão para editar colaboradores.');
           redirect(base_url());
        }
        $this->load->library('form_validation');
        $this->data['custom_error'] = '';

        if ($this->form_validation->run('colaboradores') == false) {
            $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">' . validation_errors() . '</div>' : false);
        } else {
            $data_admissao = $this->input->post('data_admissao');
			$data_demissao = $this->input->post('data_demissao');
			
			$foto = $this->do_upload();

        	$file = $foto['file_name'];
        	$url_foto = base_url().'assets/fotos/'.date('d-m-Y').'/'.$file;

            try {

            }catch (Exception $e) {
               $data_admissao = date('Y/m/d');
			   $data_demissao = date('Y/m/d');
			   $data_inicio_aviso = date('Y/m/d');
			   $data_fim_aviso = date('Y/m/d');
			   $data_inicio_ferias = date('Y/m/d');
			   $data_fim_ferias = date('Y/m/d');
			   $data_abandono1 = date('Y/m/d');
			   $data_abandono15 = date('Y/m/d');
			   $data_abandono28 = date('Y/m/d');
			   $data_inicio_previdencia = date('Y/m/d');
			   $data_fim_previdencia = date('Y/m/d');
			   $data_inicio_justica_a = date('Y/m/d');
			   $data_fim_justica_a = date('Y/m/d');
			   $data_inicio_justica_i = date('Y/m/d');
			   $data_fim_justica_i = date('Y/m/d');
			   $data_inicio_licasamento = date('Y/m/d');
			   $data_fim_licasamento = date('Y/m/d');
			   $data_inicio_suspensao = date('Y/m/d');
			   $data_fim_suspensao = date('Y/m/d');
            }
		
            $data = array(
                'nome' => $this->input->post('nome'),
                'sexo' => $this->input->post('sexo'),
				'cpf' => $this->input->post('cpf'),
				'rg' => $this->input->post('rg'),
				'url_foto' => $url_foto,
				'data_nascimento' => $this->input->post('data_nascimento'),
                'rua' => $this->input->post('rua'),
                'numero' => $this->input->post('numero'),
				'complemento' => $this->input->post('complemento'),
                'bairro' => $this->input->post('bairro'),
                'cep' => $this->input->post('cep'),
                'estado' => $this->input->post('estado'),
                'cidade' => $this->input->post('cidade'),
				'telefone' => $this->input->post('telefone'),
                'celular' => $this->input->post('celular'),
                'email' => $this->input->post('email'),
				'ctps'=> $this->input->post('ctps'),
				'serie' => $this->input->post('serie'),
				'uf' => $this->input->post('uf'),
				'pis' => $this->input->post('pis'),	
				'salario' => $this->input->post('salario'),
				'banco' => $this->input->post('banco'),
				'agencia' => $this->input->post('agencia'),
				'conta' => $this->input->post('conta'),
				'jornada_trabalho'=> $this->input->post('jornada_trabalho'),
				'horario_trabalho' => $this->input->post('horario_trabalho'),
				'data_admissao' => $this->input->post('data_admissao'),
				'departamento' => $this->input->post('departamento'),
				'cargo' => $this->input->post('cargo'),
				'situacao' => $this->input->post('situacao'),
				'data_demissao' => $this->input->post('data_demissao'),
				'tipo_demissao' => $this->input->post('tipo_demissao'),
				'motivo_demissao' => $this->input->post('motivo_demissao'),
				'data_inicio_aviso' => $this->input->post('data_inicio_aviso'),
				'data_fim_aviso' => $this->input->post('data_fim_aviso'),
				'data_inicio_ferias' => $this->input->post('data_inicio_ferias'),
				'data_fim_ferias' => $this->input->post('data_fim_ferias'),
				'data_abandono1' => $this->input->post('data_abandono1'),
				'data_abandono15' => $this->input->post('data_abandono15'),
				'data_abandono28' => $this->input->post('data_abandono28'),
				'data_inicio_previdencia' => $this->input->post('data_inicio_previdencia'),
				'data_fim_previdencia' => $this->input->post('data_fim_previdencia'),
				'data_inicio_justica_a' => $this->input->post('data_inicio_justica_a'),
				'data_fim_justica_a' => $this->input->post('data_fim_justica_a'),
				'data_inicio_justica_i' => $this->input->post('data_inicio_justica_i'),
				'data_inicio_licasamento' => $this->input->post('data_inicio_licasamento'),
				'data_fim_licasamento' => $this->input->post('data_fim_licasamento'),
				'data_inicio_limaternidade' => $this->input->post('data_inicio_limaternidade'),
				'data_fim_limaternidade' => $this->input->post('data_fim_limaternidade'),
				'data_inicio_suspensao' => $this->input->post('data_inicio_suspensao'),
				'data_fim_suspensao' => $this->input->post('data_fim_suspensao'),
				'observacao' => $this->input->post('observacao'),
				'usuario_alteracao' => $this->input->post('usuario_alteracao'),
				'data_alteracao' => date('Y-m-d')
            );

            if ($this->colaboradores_model->edit('colaboradores', $data, 'idColaboradores', $this->input->post('idColaboradores')) == TRUE) {
                $this->session->set_flashdata('success','Colaborador editado com sucesso!');
                redirect(base_url() . 'index.php/colaboradores/editar/'.$this->input->post('idColaboradores'));
            } else {
                $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';
            }
        }
		
		$this->load->model('departamentos_model');
        $this->data['departamentos'] = $this->departamentos_model->getActive('departamentos','departamentos.idDepartamentos,departamentos.departamento');
		$this->load->model('cargos_model');
        $this->data['cargos'] = $this->departamentos_model->getActive('cargos','cargos.idCargos,cargos.cargo');
		
		$this->data['result'] = $this->colaboradores_model->getById($this->uri->segment(3));

        $this->data['view'] = 'colaboradores/editarColaborador';
        $this->load->view('tema/topo', $this->data);
     
    }

Upload function

		    public function do_upload(){

        if(!$this->permission->checkPermission($this->session->userdata('permissao'),'vColaborador')){
          $this->session->set_flashdata('error','Você não tem permissão para adicionar colaboradores.');
          redirect(base_url());
        }
	
    	$date = date('d-m-Y');

		$config['upload_path'] = './assets/fotos/'.$date;
	    $config['allowed_types'] = 'txt|jpg|jpeg|gif|png|pdf|PDF|JPG|JPEG|GIF|PNG';
	    $config['max_size']     = 0;
	    $config['max_width']  = '3000';
	    $config['max_height']  = '2000';
	    $config['encrypt_name'] = true;


		if (!is_dir('./assets/fotos/'.$date)) {

			mkdir('./assets/fotos/' . $date, 0777, TRUE);

		}

		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload())
		{
			$error = array('error' => $this->upload->display_errors());

			$this->session->set_flashdata('error','Erro ao fazer upload do arquivo, verifique se a extensão do arquivo é permitida.');
            redirect(base_url() . 'index.php/colaboradores/adicionar/');
		}
		else
		{
			//$data = array('upload_data' => $this->upload->data());
			return $this->upload->data();
		}
	}

  • I included the upload function in the example above, for better understanding... Someone else can help, I tried to do as Daniel said and I couldn’t do it

2 answers

0


I always put it like this:

if (!empty($_FILES['userfile']['name'])) {
     //definicoes do UPLOAD aqui
}

That way, it only uploads if I upload a file

  • i got it. !

  • finalizes the question and marks the answer so that the solution can be used by other people

0

Separates the insertion of the image in the database and only executes the update if the user has uploaded something.

  • In the controller, I tried to do this: if($url_photo != null){ $data = array( ... ;... Since if the input file is not null, it updates and if it is null, it does not update. But it didn’t work @Daniel

  • Because it ta by inserting null into the database, creates a separate function for uploading and saving the image, so only run this function if the image input is "filled"

  • Based on the above, Do you have any suggestions? I’ve tried using the same upload function and didn’t give. Includes in the post the upload function I am using

Browser other questions tagged

You are not signed in. Login or sign up in order to post.