Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14191 articles
Browse latest View live

Automatic Project Updating

$
0
0
Hi all! I have a new module to share that I'm pretty excited about. Been working on this one a long time, and there will be some more features to come but I wanted to get the initial version out...

Tatter\Patches
Do you find it hard to keep all your project files consistent with the framework versions? Do you release libraries and modules that require developers to update their projects regularly? Let Patches help!
Patches is a module for updating CodeIgniter 4 projects. It will analyze your project code against the vendor releases (current and updated) and help you patch files.
Did you know that moving from version 4.0.2 to version 4.0.3 update 11 files in your project root? https://github.com/codeigniter4/framewor...2...v4.0.3
If you updated with Patches these would be handled for you!

Easy to use 2-step process:
1. Install the module with Composer:
Code:
> composer require --dev tatter/patches

2. Use the CLI command to update:
Code:
> php spark selfupdate

That's it! Visit the GitHub repo for more advanced configuration options, a play-by-play example of use, and the source code:

https://github.com/tattersoftware/codeigniter4-patches
https://packagist.org/packages/tatter/patches

+++++++++++++++++++++++

As always your feedback is very welcome! Feel free to discuss here, or submit feature requests and bug reports over at Github. Thanks for reading!

validation custom error not working in saved rules

$
0
0
PHP Code:
    //--------------------------------------------------------------------
    // Rules
    //--------------------------------------------------------------------
    
public $merchant_register = [
        
'email' => [
            
'label' => 'Email Address'
            
'rules' => 'trim|required|valid_email|is_unique[merchant.email]'
            
'errors' => [
                
'is_unique' => 'Your email address has been registered'
            
]
        ],
        
'password' => [
            
'label' => 'Password'
            
'rules' => 'trim|required|string|min_length[8]|max_length[30]'
        
],
        
'confirm_password' => [
            
'label' => 'Confirm Password'
            
'rules' => 'required|matches[password]'
        
],
        
'mobile' => [
            
'label' => 'Mobile No'
            
'rules' => 'trim|required|numeric|min_length[10]'
        
]
    ]; 

the default error was the one shows in the screen when i put existing email.
this is saved rule in :

PHP Code:
<?php namespace Config;

class Validation 

and run by this command which is working good. just the custom error not showing.


PHP Code:
$validation $data['validation']->run($input'merchant_register'); 

Handling Redirect

$
0
0
Hi!

How do you handle redirect in CI4?

I have multiple pages with forms. I tried to redirect back the user to same form if there are errors, or even if it was submitted completely.

Here's the problem.

User filled up 2 or more forms (different browser tabs). If user submit form A, it will be redirected to that same form. However, if he submit the another form (say, form B), instead of redirecting it back to that same form, Codeigniter will redirect it to the old form submitted which is the form A. If you user submit form C, it will redirect to form B.

I checked this documentation but the behavior is still the same.

Tried the code below already but still the same.

PHP Code:
// Go back to the previous page
return redirect()->back();

// Go to specific UI
return redirect()->to('/admin');

// Go to a named/reverse-routed URI
return redirect()->route('named_route');

// Keep the old input values upon redirect so they can be used by the `old()` function
return redirect()->back()->withInput();

// Set a flash message
return redirect()->back()->with('foo''message'); 


How do I ensure that the user will be redirected to the same form regardless of how many forms opened or submitted?

insert() return null

$
0
0
Hello,
i using CI4 and i call method insert() and i set all required params but function return 0! why? how i can get error message if is exist!
My code is:

namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;

class UserModel extends Model
{

    protected $table = 'users';
protected $primaryKey = 'id';
    protected $allowedFields = ['role', 'email','password','display_name','active','token'];
protected $useSoftDeletes = true;
protected $returnType = 'array';
protected $useTimestamps = true;
    protected $createdField  = 'created_at';
protected $deletedField  = 'deleted_at';



------------------------------- 
$signup_email=$this->request->getVar('signup_email');
$signup_password=$this->request->getVar('signup_password');
$signup_password_confirmation=$this->request->getVar('signup_password_confirmation');
$val = $this->validate([
'signup_email' => ['label' => 'Email', 'rules' => 'trim|required|valid_email'],
'signup_password' => ['label' => 'Password', 'rules' => 'trim|required'],
'signup_password_confirmation' => ['label' => lang('app.field_confirm_password'), 'rules' => 'trim|required|matches[signup_password]']
]);
if (!$val)
{

$validation=$this->validator;
$error_msg=$validation->listErrors();
$res=array("error"=>true,"validation"=>$error_msg);
}
else{
$UserModel=new UserModel();

$data = [
'display_name' => $signup_email,
'email'  => $signup_email,
'password'  => md5($signup_password),
'role'=>'customer',
'active'=>'no'

];
$user_id =$UserModel->insert($data);
$res=array("error"=>false,"validation"=>$user_id);

}

some kind of simple CMS

$
0
0
I was thinking of perhaps some kind of simple CMS for small businesses to make a website with pages like homepage, map, menu prices, contact etc... but perhaps this is a bit complex just to showcase the framework. Another idea would be a simple forum, but perhaps someone would have a better idea for a simple project.

I've had a course module and then practical training experience working with the Microsoft's ASP.NET MVC with C#. That was ok, but I'm a Linux guy and have coded (badly) with php as a hobby for some years. I would much rather further my knowledge of php and MVC design architecture which I really liked using with ASP.NET. My front end skills are also up to scratch.

AJAX ARRAY

$
0
0
Hello there. I'm from Turkey. I use google translate because i don't speak english.

I am sending an array to the Controller with AJAX. There are 3 different IDs in the array I sent. I will pull data from the database with these IDs, but I don't know how to separate them.

Ajax
Code:
$.ajax({
            url: '<?php echo base_url('varyasyonlar/o_getir') ?>',
            type: 'POST',
            data: {opts: opts},
            dataType: 'JSON',
            cache: false,
            success: function (data) {
                const toast = swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    padding: '2em'
                });

                toast({
                    type: 'success',
                    title: 'Çalıştı.',
                    padding: '2em',
                })
            },
            error: function (data) {
                swal({
                    title: 'Bir hata oluştu!',
                    type: 'error',
                    padding: '2em'
                });
            }
        });

Controller
Code:
public function o_getir() {
        $data = $this->input->post('opts');

        $this->varyasyonlar_model->o_get2($data);
       
        foreach ($data as $key => $row) {
            $output['opsiyon_id'][$key] = $row->opsiyon_id;
            $output['opsiyon_baslik'][$key] = $row->opsiyon_baslik;
        }

        echo json_encode($output);    
    }

Model
Code:
public function o_get2($data) {

        for ($i = 0; $i < count($data); $i++) {
            $this->db->where('varyasyon_id', $data[$i]);
            $result[] = $this->db->get('opsiyonlar')->result_array();
        }
       
        return $result;
    }

IDs in Array
[Image: s6OuIG.png]

The data I want to bring from the database.
[Image: IVwJGn.png]

The data of each ID must be in different arrays.

Parser function (parseConditionals) error - JS in HTML with condition IF

$
0
0
Hello,
I think I found a view parser problem. The problem occurs according to the error code when substituting the phrase "{if" in the HTML code that contains the JS code. There is no '{if' tag used to be replaced by the parser, but it tries to do it.

My JS code in HTML:
                success: function (data) {
                  if (data.code == true) {
                    clock_time = clock_time_session;
                  }

As you can see, this is a piece of AJAX code written before the end of BODY in HTML.

The parser lets go when I do this trick:
                success: function (data) {
// -> Added Comment (fix), finaly pattern not matched
                  if (data.code == true) {
                    clock_time = clock_time_session;
                  }

After analyzing the regex that is to replace the {if} {elseif} {else} etc ... it looks like a syntax error in the saved regex.

File system/View/Parser.php:
Pattern line 524/868 in the parseConditionals function:
$pattern = '/\{\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms';

My Fix:
$pattern = '/\{(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*\}/ms';

CUT: "\s*" -> ""

It seems to me that the use of spaces between "{" and "if" should not be allowed, which also translates into a parser crash through your own JS code in BODY HTML.

Please check the Framework again for using the view parser.

I'm using the latest stable version 4.0.3.


A little note.

I noticed that you also allow {   else  } or {  endif} tags. Since you write in the documentation specifically {else} or {endif} instead of what I gave above, I think there is no point in allowing additional whitespace or new lines - no sense ...

ini_set(): A session is active

$
0
0
Code:
Severity: Warning

Message: ini_set(): A session is active. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

My system : 
PHP 7.3.11 on Mac OS Catalina

After upgrading from CI 2.2.1 to 3.1.11 version I keep getting these Warnings, I have no session_start() calls in my code, if I set ENVIRONMENT = production the warnings stop, I need to keep ENVIRONMENT = development to test the app but I can't remove these warnings from sessions.

My Session config:
PHP Code:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'credsession';
$config['sess_expiration'] = 0;
$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE

I tried commenting session_start() on line 143 of "system/libraries/Session/Session.php" and the warnings stop, but I don't think that's a good solution.
I removed the system folder and pasted the system 3.1.11 version into my app, followed all upgrading instructions on https://www.codeigniter.com/userguide3/i...e_300.html 

Could this be a php 7.3.11 problem?

Array to string conversion

$
0
0
Hola

Tengo el siguiente problema en CI4, cuando quiero generar un nuevo usuario en mi db desde un formulario, devuelve el siguiente error:

Conversión de matriz a cadena

pero al editar / modificar este usuario, lo guarda en la base perfectamente sin errores

Este es mi código:

PHP Code:
<?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();
?>

PHP Code:
    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;

    } 

PHP Code:
<?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 $deletedField  'deleted_at';

    # -----------------------------------------------------------------
    # Pongo todas las reglas de validacion
    # -----------------------------------------------------------------
    protected $validationRules    = array(
        # Valido el name
        # le digo que sea requerido y (|) que sea alfanumerico y que tenga un minimo de 3 caracteres
        'name' => 'required|alpha_numeric_space|min_length[3]',
        # Valido el email, que sea requerido, de timo email y unico
        'email' => 'required|valid_email|is_unique[users.email]'
    );

    # -----------------------------------------------------------------
    # Si Falla alguna de las validaciones entonces enviame este mensaje
    # -----------------------------------------------------------------
    protected $validationMessages = [
        'email' => [
            'is_unique' => 'Ese correo ya se encuentra registrado'
        ]
    ];

    protected $skipValidation     false

form_dropdown() function

$
0
0
any idea to set the first option become hidden?

External Javascript

$
0
0
Hi,
I am using CI4

My preferred way of using javascript/jquery is to use external .js files

Code:
<script src="<?php echo base_url('includes/common/js/myfunctions.js'); ?>" ></script>


rather than including the javascript/jquery in the page
Code:
$.ajax({
    type: "POST",
    processData: false, // important
    contentType: false, // important
    data: data,
    url: "<?= base_url('file/function'); ?>",
    dataType: "script",
    beforeSend: function() {
        $('.processing').show();
    },
    complete: function() {
        $('.processing').hide();
    },
    success: function (data) {
        alert(data);            
    },
    error: function(data) {
        alert('error '+data);
    },
});
Does codeigniter 4 address any of the obvious issues that would arise is if I was to use try and use codeigniter helpers like base_url() in an external js file???

About global mysql connection on CI 4

$
0
0
Hello there,

I was using CI 3, but today i downloaded version 4. I could not set $db variable global to use every function?

Anyone can give me example code ?

Thanks...

PHP Code:
<?php namespace App\Controllers;

ini_set('display_errors',1);
class 
Home extends BaseController
{
    public function 
__construct()
    {

        
$db = \Config\Database::connect();
}
    public function 
index()
    {
        
$query $this->db->query('SELECT * FROM cats');
    
  $results $query->getResult();
print_r($results);
$data = [];
    
//    $data['cats'] = $results;
        
return view('index');

    }


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


CI4 in localhost

$
0
0
hi , sorry for english im new in ci4 , in ci3 when i unzip the project in my localhost i can access by the browser visit the url http://localhost/myproject , now in ci4 i must add at the url the public http://localhost/myproject/public  but i have the error 
Code:
[color=#333333][size=small][font=Tahoma, Verdana, Arial, sans-serif][color=#222222][size=xx-large]Whoops![/size][/color]

[color=#777777][size=large]We seem to have hit a snag. Please try again later...[/size][/color][/font][/size][/color]

my .env is in development mode .

If i run the command php spark serve it work fine , Why ?

CI4 in shared hosting

$
0
0
Hi , i upload an application in ci4 to a shared hosting in a subfolder  , when i try to access it i have this problem :


ErrorException

realpath(): open_basedir restriction in effect. File(/var/www/html) is not within the allowed path(s):

This is my url : http://eventisportivi1.altervista.org/co..._4/public/

CI 4 - beginner problems

$
0
0
Hello

Im trying to make a switch from CI3 to CI4. I must admit that I really like ci3, however ci4 looks great and I'm looking forward to make an apps with new version o ci.

At the beginning, for the testing purspose, I'm trying to write a really simple auth libarary. In CI3 i would create MyAuth in application/library:
PHP Code:
class MyAuth
{
...

public function 
getName(){
return 
$this->firstName.' '.$this->lastName;


in controller i could load it
PHP Code:
public function testing
{
    
$this->load->library('myauth');
    return 
view('file',$this->outputData);


and in view I could print it like that:
PHP Code:
echo $this->myauth->getName(); 

Is there any way to do the same in ci 4?

Sorry but I can't find many informations about creating libraries in CI 4.

Codeigniter 4 - Naming Convention & Style Guide

$
0
0
Stackoverflow link: https://stackoverflow.com/questions/6212...tyle-guide

I have found contradictory rules about Codeigniter 4 naming conventions & style guide. For example following are two guides about class names: 
[color=var(--blue-700)]Controller class names MUST start with an uppercase letter and [b]ONLY the first character can be uppercase[/b].[/color]
Can somebody clarify about [b]method[/b] & [b]class[/b] naming convention and whether we have different requirements for controllers, models,helpers, etc?
Can I use following convention:
All Classes: Any_class
Methods: any_method
As URL should always be in lowercase so I think camelCase method names should not be used. What is your opinion?
I know its a matter of personal choice but I want to follow best practices.

Codeigniter4 Installazione su altervista.org

$
0
0
qualcuno ha messo CI4 su altervista.org ?
Cosa va modificato perche di default non gira ... Sad

I always get mysqli_sql_exception #2002

$
0
0
Hi, I am new to Ci. I have completed a few tutorials and everything works OK until I get to connecting to MySQL. I am using MAMP pro, a Macbook pro and Mac OS. 

mysqli_sql_exception #2002

SYSTEMPATH/Database/MySQLi/Connection.php at line 225

---------------

This is what I have done so far to debug:

I have found a way to get the page to load, run PHP and display data from the database -> I turned on 'Allow network Access to MySQL' in MAMP and ran the index.php file in the public folder. The error went away and I see the page loading -> so the code is not incorrect. Interestingly, when I 'Allow network Access to MySQL' and try to view the project in my browser, I get the MySQL connection error.

Every time, I try to 'php spark serve' and run the application on localhost:8080 -> I get the error mysqli_sql_exception #2002 where Ci can't connect to MySQL.

--------------

I have seen a fgew other posts on Stack Exchange and also on the Ci form about this. Does anyone know how to fix it?

I am assuming, I should always use 'php spark serve' and not open the file in a path within my htdocs?

.png   Screenshot 2020-06-01 at 14.57.10.png (Size: 120.56 KB / Downloads: 0)

.png   Screenshot 2020-06-01 at 14.57.36.png (Size: 143.98 KB / Downloads: 0)

Netbeans Plugin for CodeIgniter 4

$
0
0
Hello Guys,
I am kind of stuck with netbeans IDE. I looked for netbeans plugin for CodeIgniter 4 if someone working on it. If no one started the task then I can start the development from myself. If you're sure no one else is working with that, then I can start it as early as possible.
Have a good day!

display error message

$
0
0
Hello,
how i can know what's the error in my code if i see this: 
Whoops!

We seem to have hit a snag. Please try again later...

in file log i not see any detailed error!
Viewing all 14191 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>