codeigniter 18

Codeigniter 4馃敟 [18.- Editar registros]

En este tutorial vamos trabajar con la edici贸n de registros. Codigo en github.com: https://github.com/programadornovato/codeigniter4/commit/8257400e484ec77cc012490a101b3b1

//app/Controllers/Home.php
<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\UserModel;

class Home extends BaseController
{
	public function __construct(){
		helper('form');
	}
	public function guarda(){
		$userModel=new UserModel($db);
		$request= \Config\Services::request();
		$data=array(
			'name'=>$request->getPostGet('name'),
			'email'=>$request->getPostGet('email'),
		);
		if($request->getPostGet('id')){
			$data['id']=$request->getPostGet('id');
		}
		if($userModel->save($data)===false){
			var_dump($userModel->errors());
		}
		if($request->getPostGet('id')){
			$users=$userModel->find([$request->getPostGet('id')]);
			$users=array('users'=>$users);
			$estructura=view('estructura/header').view('estructura/formulario',$users);	
		}
		else{
			$users=$userModel->findAll();
			$users=array('users'=>$users);
			$estructura=view('estructura/header').view('estructura/body',$users);
		}
		return $estructura;

	}
	public function editar(){
		$userModel=new UserModel($db);
		$request= \Config\Services::request();
		$id=$request->getPostGet('id');
		$users=$userModel->find([$id]);
		$users=array('users'=>$users);
		$estructura=view('estructura/header').view('estructura/formulario',$users);
		return $estructura;

	}

	public function formulario(){
		$estructura=view('estructura/header').view('estructura/formulario');
		return $estructura;
	}
	public function index()
	{
		$userModel=new UserModel($db);
		//$users=$userModel->find([1,2]);
		//$users=$userModel->findAll();
		//$users=$userModel->where('name','maria')->findAll();
		//$users=$userModel->findAll(2,3);
		//$users=$userModel->withDeleted()->findAll();
		/*
		$data=[
			'name'=>"programador1",
			'email'=>"pr[email protected]"
		];
		$userModel->insert($data);
		
		$data=[
			'name'=>"programador2",
			'email'=>"[email protected]"
		];
		$userModel->update(10,$data);
		
		$data=[
			'name'=>"yo"
		];
		$userModel->update([2,3],$data);
		
		$userModel->whereIn('id',[4,5,10])
		->set(['name'=>'yo tambien'])
		->update();
		
		$data=[
			'name'=>"programador11",
			'email'=>"[email protected]"
		];
		$userModel->save($data);
		
		$data=[
			'id'=>"12",
			'name'=>"programador yo tambien",
			'email'=>"[email protected]"
		];
		$userModel->save($data);
		*/
		//$userModel->delete([2,4,5]);
		//$userModel->where('id',10)->delete();
		//$userModel->purgeDeleted();
		/*
		$data=[
			'name'=>"programadorvalido nuevo 2",
			'email'=>"[email protected]"
		];
		if($userModel->save($data)===false){
			var_dump($userModel->errors());
		}
		*/
		/*
		$users=$userModel->asArray()->where('name','programador11')
		->orderBy('id','asc')
		->findAll();
		var_dump($users);
		*/
		$users=$userModel->findAll();
		
		$users=array('users'=>$users);
		$estructura=view('estructura/header').view('estructura/body',$users);
		return $estructura;
		
	}

	//--------------------------------------------------------------------

}







//app/Models/UserModel.php
<?php namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
        protected $table      = 'users';
        protected $primaryKey = 'id';

        protected $returnType = 'array';
        protected $useSoftDeletes = true;

        protected $allowedFields = ['name', 'email'];

        protected $useTimestamps = false;
        protected $createdField  = 'created_at';
        protected $updatedField  = 'updated_at';
        
        protected $validationRules    = [
                'name' => 'required|alpha_numeric_space|min_length[3]',
                'email' =>'required|valid_email|is_unique[users.email]'
        ];
        protected $validationMessages = [
                'email' =>[
                        'is_unique'=>'Lo sentimos. Tu correo ya esta siendo usado por otro usuario'
                ]
        ];
        
        protected $skipValidation     = true;
        //protected $beforeInsert=['agregaAlgoName'];
        //protected $beforeUpdate=['agregaAlgoName'];
        protected function agregaAlgoName(array $data){
                $data['data']['name']=$data['data']['name']." algo";
                return $data;
        }
}







//app/Views/estructura/body.php 
<body>
<div class="container">
    <div class="row">
        <a href="<?php echo base_url(); ?>home/formulario" class="btn btn-info" role="button" >Nuevo</a>
    </div>
    <div class="row">

    
        <table  class="table">
        <tr>
        <th scope="col">id</th>
        <th scope="col">name</th>
        <th scope="col">email</th>
        <th scope="col">deleted</th>
        <th scope="col">acciones</th>
        </tr>
        <?php
        foreach($users as $user){
            echo "<tr  scope='row' >";
            echo "<td>".$user['id']."</td>";
            echo "<td>".$user['name']."</td>";
            echo "<td>".$user['email']."</td>";
            echo "<td>".$user['deleted']."</td>";
            echo "<td>";
            ?>
            <a href="<?php echo base_url(); ?>home/editar?id=<?php echo $user['id']; ?>" class="btn btn-warning" role="button" ><i class="fa fa-pencil-square-o"></i></a>
            <?php
            echo form_button(array('name'=>'borrar','type'=>'submit','class'=>'btn btn-danger','content'=>'<i class="fa fa-trash"></i>'));
            echo "</td>";
            echo "</tr>";
        }
        ?>
        </table>
    </div>
</div>
</body>
</html>






//app/Views/estructura/formulario.php
<div class="container">
<?php
echo form_open('/home/guarda');
if(isset($users)){
    $name=$users[0]['name'];
    $email=$users[0]['email'];
}
else{
    $name="";
    $email="";
}
?>
<div class="form-group">
<?php
echo form_label('Nombre','name');
echo form_input(array('name'=>'name','placeholder'=>'Nombre','class'=>'form-control','value'=>$name));
echo "<br>";
echo form_label('Email','email');
echo form_input(array('name'=>'email','placeholder'=>'Email','class'=>'form-control','value'=>$email));
echo "<br>";
echo form_submit('guarda','Guardar','class="btn btn-primary"');
if(isset($users)){
    echo form_hidden('id',$users[0]['id']);
}

?>
</div>
<?php

echo form_close();
?>
</div>

Codeigniter 4? [18.- Editar registros]

#Codeigniter4 #php7 #backend #Codeigniter #php .
? Esta lista de reproducci贸n: https://www.youtube.com/playlist?list=PLCTD_CpMeEKTFN5TDeOP-wP_hU0_9VoWg
.
Codigos en gdrive: https://drive.google.com/file/d/1awbG6jI40IO0N68fgjLUwNFpsTC3wIHj/view?usp=sharing .
Gracias por apoyar este canal: https://www.patreon.com/programadornovato?fan_landing=true .
? Facebook: https://facebook.com/ProgramadorNovatoOficial
? Twitter: https://twitter.com/programadornova
? Linkedin: https://www.linkedin.com/in/programadornovato/
? Instagram: https://www.instagram.com/programadornovato/

Deja un comentario

Tu direcci贸n de correo electr贸nico no ser谩 publicada. Los campos obligatorios est谩n marcados con *