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

Form Validation Allowing Empty Strings To Be Stored Instead of Null

$
0
0
I'm trying to get form validation to work at the model level. I have three fields, id, name and email, and I have them all set to required.

I'm using the CI 4 Entity class, so on an incoming request, I get the JSON, fill my new Entity on creation, and then pass to the model. 

No matter what I do, for the fields name and email (set to varchar 150 and not NULL in SQL), when I try to insert, name and email are stored as empty strings when I don't include them in my JSON (for instance, if I pass id alone).

How can I make it so that if the name and email keys are not passed, the required error is shown?

Model:
PHP Code:
<?php

namespace Modules\User\Models;

use 
CodeIgniter\Model;

class 
UserModel extends Model
{
    protected $table 'users';
    protected $primaryKey 'id';
    protected $returnType 'Modules\User\Entities\User';

    protected $useSoftDeletes true;
    protected $allowedFields = ['id''name''email''password'];

    protected $useTimestamps true;
    protected $createdField 'created_at';
    protected $updatedField 'updated_at';
    protected $deletedField 'deleted_at';

    protected $validationRules = [
        'id' => 'required|integer|is_unique[users.id]',
        'name' => 'required',
        'email' => 'required|valid_email|is_unique[users.email]
    ];
    protected $validationMessages = [
        '
id' => [
            '
required' => 'An ID is requiredThis is normally a Podio Item ID.',
            '
integer' => 'ID must be an integer.',
            '
is_unique' => 'A record with this ID already exists.'
        ],
        '
name' => [
            '
required' => 'A name is required.'        ],
        '
email' => [
            '
required' => 'An email address is required.',
            '
valid_email' => 'You must enter a valid email address.',
            '
is_unique' => 'The email address already exists in the system.'
        ]
    ];

    protected $skipValidation = false;


Controller:
PHP Code:
public function create()
    {
        $json $this->request->getJSON(true);

        if ($json == null) {
            $response = array(
                'code' => 400,
                'errors' => array('Request cannot be empty.')
            );

            return $this->respond($response200);
        }

        $user = new User($json);

        if ($this->model->insert($user) === false) {
            $response = array(
                'code' => 400,
                'errors' => $this->model->errors()
            );

            return $this->respond($response200);
        }

        $response = array(
            'code' => 200,
            'message' => 'User has been created.'
        );

        return $this->respond($response200);
    

protected $DBGroup = 'ywl_data';

$
0
0
Hi,

I have some DBgroups declared in App/Config/Database:

// localhost
public $ywl_config = [
'DSN'      => '',
'hostname' => 'localhost',
'username' => 'yachtworklist',
'password' => 'MbiHClUFBjDv6eRE',
'database' => 'ywl_config',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug'  => (ENVIRONMENT !== 'production'),
'cacheOn'  => false,
'cacheDir' => '',
'charset'  => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre'  => '',
'encrypt'  => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port'    => 3306,
];

public $ywl_data = [
'DSN'      => '',
'hostname' => 'localhost',
'username' => 'yachtworklist',
'password' => 'MbiHClUFBjDv6eRE',
'database' => 'ywl_data',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug'  => (ENVIRONMENT !== 'production'),
'cacheOn'  => false,
'cacheDir' => '',
'charset'  => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre'  => '',
'encrypt'  => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port'    => 3306,
];


and I want that each migration file call their DataBase, but all of migrations files call DataBase defined in $defaultGroup

class BoatDecks extends Migration
{
protected $DBGroup = 'ywl_data'; // doesn't work!!!!

public function up()
{
$this->forge->addField([
'id' => [
'type' => 'SERIAL'
],
'id_boat' => [
'type' => 'INT',
'constraint' => '4'
],
'deck_name' => [
'type' => 'VARCHAR',
'constraint' => '25'
]
]);

$this->forge->addField("created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP()");
$this->forge->addField("updated_at TIMESTAMP NULL");
$this->forge->addField("deleted_at TIMESTAMP NULL");
$this->forge->addKey('id', TRUE);
$this->forge->createTable('ywl_data_boat_decks');
}

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

public function down()
{
$this->forge->dropTable('ywl_data_boat_decks');
}
}


thank's!

Reset Password Failing

$
0
0
I'm are updating a project from ci2 to ci3 and are having an issue with the reset password - I had thought it was a fairly simple fix to update the url in the password email - which does take you to the correct page however the password won't actually reset. First I was receiving the error message:

An Error Was Encountered

This form post did not pass our security checks.

I followed the advice on stackoverflow

Now I am not receiving an error message but when I test the login with the updated password it fails.

I am also having an issue where if you select log out it does not actually log the person out.

The only warning there is in the logs is Severity: Warning --> ini_set(): A session is active. You cannot change the session module's ini settings at this time
Does anybody have any ideas?
Many Thanks

CI developer Available.

$
0
0
Hello sir/mam.

I have more then 10 years of experience in web application development. I have worked as Rest Api developer for (Web, IOS, Android). I am good team player. I dont have problem in working with geographical displaced team with different timezone.


Good in understanding requirement. I may not be a good programmer in your point of view but I am good implementer for sure. You can contact with me here or information given in signature.

How do I upload a file with CURLRequest?

$
0
0
I am unable to implement a curl call using the library. I'm trying to write the following command using the library:
Code:
curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'
If you are interested in the documentation, here is a link. I'm trying to share an image and stuck on the upload part. This is what I have tried and I am getting all sorts of errors. Mostly bad requests but from time to time I would get an ssl error

PHP Code:
$client = \Config\Services::curlrequest([], nullnullfalse);
                                    try {
                                        $response $client->request('post'$uploadURL, [
                                        'headers' => [
                                            'Authorization' => 'Bearer ' $Social->AuthorizationToken,
                                            'X-Restli-Protocol-Version' => '2.0.0',
                                            'Content-Type' => 'multipart/form-data',
                                        ],
                                        'multipart' => [
                                            'upload-file' => new CURLFile(realpath("absolutepathtoimage.png"), "image/png""imagename.png"),
                                        ],
                                        'verify' => false
                                    
]);
                                    } catch (\CodeIgniter\HTTP\Exceptions\HTTPException $e) {
                                        var_dump($response);
                                        var_dump($e->getTrace());
                                        die();
                                    
I am inclined to just use plain curl. Perhaps this library is just not mature enough?

Codeigniter and Docker MS SQL Server on Mac

$
0
0
Hey everyone,

I have a Codeigniter site and I'm trying to connect it to a MS SQL Server I set up with Docker on my MacOS.

Does anybody have experience doing this? 

I've looked at a bunch of articles on how to do this but it's not working for me. 

In particular, I've tried following the instructions here: https://www.microsoft.com/en-us/sql-serv...ed/php/mac 

I get stuck on step 2.3 where it says to run connect.php in your terminal. 

The error I can't get away from is: 


Quote:Error: Call to undefined function sqlsrv_connect() in /Users/ryanmartin/Local Sites/docker_php/connect.php on line 10



php -v and pecl version both output PHP 7.3.8 

My PEAR version is 1.10.9. 

I also have brew and sql commands for my command line all installed. 

I just cannot for the life of my connect a PHP project to a MS SQL Server with my Mac. 

Any help would be greatly appreciated. 

Sorry if this is the wrong place to post this. This is my first post.

setup install like wordpress

$
0
0
I want to make settings to install my application like wordpress.
I tried to make a new file like wordpress.
but I have difficulty when making it.


first option :
PHP Code:
if ( ! file_exists(APPPATH.'config/my_database.php')) {

    
$data = array(
    
'$config["database_name"] = "my-name"',
    );
        //I'm having trouble creating a my_database file with values like this:
        //$config[username] = 'my-name';
        //$config[userpass] = 'my-pass';
        //etc.

        
if ( ! write_file(APPPATH.'config/my_database.php'$data)) {
        echo 
'Unable to write the file';
    } else {
        echo 
'File written!';
    }




second option  :
PHP Code:
if ( ! file_exists(APPPATH.'config/database.php')) {

    if (
copy(APPPATH.'config/database_example.php'APPPATH.'config/database.php')) {
            // I'm having a problem here, before copying data $db['defult'] = array for database.php
            // changed according to the configuration form later.
            // I tried using the file_put_contents() function but failed.

        
echo 'Copy Success';
    } else {
        echo 
'Copy Failed!';
    }


or if there is another way let me know

Please help and thank you Smile

Need help populating database with products

$
0
0
Hi everyone,

I need to learn how to quickly populate my shopping cart database with products. Is there a tutorial suitable for CI or is any kind soul willing to guide me or point me in the right direction? I've been playing with the db products and category tables for some days now but no joy.

Thanks for any help.

localisation

$
0
0
I am writing an application but I have no idea how it could be translated. Do you have an exemple somewhere how to do it simply I imagine all label should be remplace by something

I ask that in CI4 forum because I am starting using CI4 not CI3

Update Array values to DB

$
0
0
I was trying to update the values as array. The problem that i face is it gets added to the values instead of getting updated.

Eg. when i did insert (Add) in country section i had India,Australia. Now i tried to update it to USA,UK.
But my update goes and inserts as India,AustraliaUSA,UK => exactly like this.

My code is,

Code:
public function edit($id)
{

    // If there is no testimonial in this id, then redirect
    $tot = $this->Model_movie->movie_check($id);
    if(!$tot) {
    redirect(base_url().'admin/movie/view');
        exit;
    }
     
      $data['setting'] = $this->Model_common->get_setting_data();
$error = '';
$success = '';


if(isset($_POST['movie_edit']))
{

$valid = 1;

$this->form_validation->set_rules('movie_name', 'Worldwide Name', 'trim|required');
$this->form_validation->set_rules('movie_original_name', 'Original Name', 'trim|required');
$this->form_validation->set_rules('movie_description', 'Description', 'trim|required');
$this->form_validation->set_rules('movie_stars', 'Enter Casts', 'trim|required');
$this->form_validation->set_rules('movie_director', 'Director', 'trim|required');
$this->form_validation->set_rules('movie_trailer', 'Trailer', 'trim|required');
$this->form_validation->set_rules('release_date', 'Release Date', 'trim|required');
$this->form_validation->set_rules('release_year', 'Release Year', 'trim|required');
$this->form_validation->set_rules('movie_genre[]', 'Select Genres', 'trim|required');
$this->form_validation->set_rules('movie_rating', 'Enter Rating', 'trim|required');
$this->form_validation->set_rules('movie_country[]', 'Select Country', 'trim|required');
$this->form_validation->set_rules('movie_runtime', 'Enter Runtime', 'trim|required');
$this->form_validation->set_rules('is_featured', 'Is Featured', 'trim|required');

if($this->form_validation->run() == FALSE) {
$valid = 0;
                $error .= validation_errors();
            }

            $path = $_FILES['movie_image']['name'];
    $path_tmp = $_FILES['movie_image']['tmp_name'];

    if($path!='') {
        $ext = pathinfo( $path, PATHINFO_EXTENSION );
        //$file_name = basename( $path, '.' . $ext );
        $file_name = basename( $path );
        $ext_check = $this->Model_common->extension_check_photo($ext);
        if($ext_check == FALSE) {
            $valid = 0;
            $error .= 'You must have to upload jpg, jpeg, gif or png file for featured photo<br>';
        }
    }

    if($valid == 1)
    {
    $data['movie'] = $this->Model_movie->get_movie($id);


    $val_movie_genre = $this->input->post('movie_genre');
        foreach($val_movie_genre as $row)
{
  //$movie_genre .= $row . ', ';
$movie_genre = $movie_genre . $row. ",";
}
$movie_genre = substr($movie_genre, 0, -1);

$val_movie_country = $this->input->post('movie_country');
foreach($val_movie_country as $row1)
{
  //$movie_country .= $row1 . ', ';
$movie_country = $movie_country . $row1. ",";
}
$movie_country = substr($movie_country, 0, -1);


    if($path == '') {
    $form_data = array(
'movie_name'        => $_POST['movie_name'],
'movie_original_name' => $_POST['movie_original_name'],
'movie_image'      => $final_name,
'movie_description'    => $_POST['movie_description'],
'movie_stars'    => $_POST['movie_stars'],
'movie_director'    => $_POST['movie_director'],
'movie_trailer'    => $_POST['movie_trailer'],
'release_date'    => $_POST['release_date'],
'release_year'    => $_POST['release_year'],
//'movie_genre'    => $_POST['movie_genre'],
'movie_genre'    => $movie_genre,
'movie_rating'    => $_POST['movie_rating'],
//'movie_country'    => $_POST['movie_country'],
'movie_country'    => $movie_country,
'movie_runtime'    => $_POST['movie_runtime'],
'is_featured'    => $_POST['is_featured']
            );
            $this->Model_movie->update($id,$form_data);
}
else {
unlink('./public/images/movies/'.$data['movie']['movie_image']);

//$final_name = 'testimonial-'.$id.'.'.$ext;
//$final_name = $path.'.'.$ext;
$final_name = $path;
        move_uploaded_file( $path_tmp, './public/images/movies/'.$final_name );


        $val_movie_genre = $this->input->post('movie_genre');
        foreach($val_movie_genre as $row)
{
  //$movie_genre .= $row . ', ';
$movie_genre = $movie_genre . $row. ",";
}
$movie_genre = substr($movie_genre, 0, -1);

$val_movie_country = $this->input->post('movie_country');
foreach($val_movie_country as $row1)
{
  //$movie_country .= $row1 . ', ';
$movie_country = $movie_country . $row1. ",";
}
$movie_country = substr($movie_country, 0, -1);

        $form_data = array(
'movie_name'        => $_POST['movie_name'],
'movie_original_name' => $_POST['movie_original_name'],
'movie_image'      => $final_name,
'movie_description'    => $_POST['movie_description'],
'movie_stars'    => $_POST['movie_stars'],
'movie_director'    => $_POST['movie_director'],
'movie_trailer'    => $_POST['movie_trailer'],
'release_date'    => $_POST['release_date'],
'release_year'    => $_POST['release_year'],
//'movie_genre'    => $_POST['movie_genre'],
'movie_genre'    => $movie_genre,
'movie_rating'    => $_POST['movie_rating'],
//'movie_country'    => $_POST['movie_country'],
'movie_country'    => $movie_country,
'movie_runtime'    => $_POST['movie_runtime'],
'is_featured'    => $_POST['is_featured']
            );
            $this->Model_movie->update($id,$form_data);
}

$success = 'Movie is updated successfully';
$this->session->set_flashdata('success',$success);
redirect(base_url().'admin/movie/view');
    }
    else
    {
    $this->session->set_flashdata('error',$error);
redirect(base_url().'admin/movie/edit'.$id);
    }
         
} else {
$data['movie'] = $this->Model_movie->get_movie($id);
      $this->load->view('admin/view_header',$data);
$this->load->view('admin/view_movie_edit',$data);
$this->load->view('admin/view_footer');
}

}


But the Add option is working fine.

EDIT: code tags added for readability. See MyCode

setting the /config directory in a Docker install

$
0
0
I have loaded the following containers:
apache
php-fpm
mariaDB
bitnami/Codeigniter

My concern is with the codeigniter container. As you know the /config directory has database.php and also config.php. These have specific values for my application. Of course I have these already setup in my /application directory. But if I start the bitnami/Codeigniter container, my CI config files will not be in there. My question is this: Do I even need to use a codeigniter container? Isn't the entire Codeigniter environment already in my /application directory?? I am getting the error below.

elcome to the Bitnami codeigniter container
Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-codeigniter
Submit issues and feature requests at https://github.com/bitnami/bitnami-docke...ter/issues

Starting application ...
Creating example Codeigniter application
mysql-c ERROR [canConnect] Connection with 'root' user is unsuccessful
mysql-c ERROR [canConnect] Connection with 'root' user is unsuccessful
mysql-c ERROR [canConnect] Connection with 'root' user is unsuccessful
mysql-c ERROR [canConnect] Connection with 'root' user is unsuccessful
mysql-c ERROR [canConnect] Connection with 'root' user is unsuccessful
mysql-c INFO  Trying to connect to MySQL server
mysql-c INFO  Found MySQL server listening at mariadb:3306
Cannot connect to MySQL server:
MySQL command failed to run. Error:
ERROR 1045 (28000): Access denied for user 'root'@'172.21.0.5' (using password: NO)

Codeigniter app created
Directory /app/myapp does not exist.

Crud generating In Codeigniter-4

$
0
0
Crud Application Demo In  Codeigniter-4 Please Find below link Crud code and database table. Hope this is help full for beginners who want to explore his skills with Codeigniter-4

Crud Demo Project in Codeigniter-4 Google drive link here:

https://drive.google.com/file/d/1n1XGtkM...yhyES/view

CI 3 or CI 4 for new project

$
0
0
Hi,
I would like to know your opinion, I should use CI 4 beta and update it when the stable version has arrived or should I use version 3 and update after?

Sorry for my english

Routes loaded twice .

getEXIF error on some files...bug?

$
0
0
Almost put in a bug in GitHub, but wanted to post here first and see if it's valid:



- OS: MacOS 10.14.6

- Web server Apache/2.2.34 (local)

- PHP version 7.3.7

- CodeIgniter 4.0.0-rc.2



My Controller Code:



Code:
$image = \Config\Services::image();
$exif = $image
->withFile(WRITEPATH.'uploads/'.$newName)
->getEXIF();




Expecting the getEXIF function to return the results of exif_read_data, which it does for some files but on others the following error was logged:



CRITICAL - 2019-10-09 02:02:51 --> exif_read_data(my-jpg.jpg): Incorrect APP1 Exif Identifier Code

#0 [internal function]: CodeIgniter\Debug\Exceptions->errorHandler(2, 'exif_read_data(...', '/Directory/...', 544, Array)

#1 /Directory/framework-master/system/Images/Handlers/BaseHandler.php(544): exif_read_data('/MyFolder/...')

#2 /MyFolder/framework-master/app/Controllers/Images.php(55): CodeIgniter\Images\Handlers\BaseHandler->getEXIF()

#3 /MyFolder/framework-master/system/CodeIgniter.php(844): App\Controllers\Images->upload()

#4 /MyFolder/framework-master/system/CodeIgniter.php(335): CodeIgniter\CodeIgniter->runController(Object(App\Controllers\Images))

#5 /MyFolder/framework-master/system/CodeIgniter.php(245): CodeIgniter\CodeIgniter->handleRequest(NULL, Object(Config\Cache), false)

#6 /MyFolder/framework-master/public/index.php(45): CodeIgniter\CodeIgniter->run()

#7 {main}



I can provide it if needed.



Will be happy to file the bug in GitHub if appropriate.



Thanks,

Derek

CodeIgniter VS ZendFramework/expressive ?

$
0
0
Hello CodeIgniters,
I was about to start learning ZF3 or Expressive ,but i found it bulky in a hard way what's your thoughts ?

codeigniter4 with nginx ssl not work

$
0
0
I use the nginx config in codeigniter3,it works。

but in codeigniter4 not work



Code:
server
    {
        listen 80;
        #listen [::]:80;
        server_name www.domain.com domain.com *.domain.com;
        return 301 https://www.domain.com$request_uri;
    }

server
    {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name www.domain.com domain.com *.domain.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root /home/wwwroot/ci400rc21/public;
        #ssl on;
        ssl_certificate /etc/letsencrypt/live/www.domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/www.domain.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
        ssl_session_cache builtin:1000 shared:SSL:10m;
        # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048
        ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem;

        include enable-php.conf;

        location / {
        try_files $uri $uri/ /index.php/$args;
    }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log  /home/wwwlogs/www.domain.com.log;
    }



return 500 error



when not use ssl,
Code:
server
    {
        listen 80;
        #listen [::]:80;
        server_name www.domain.com domain.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root /home/wwwroot/ci400rc21/public;
        
        location / {
                try_files $uri $uri/ /index.php/$args;
        }
        #error_page   404   /404.html;
        location ~ [^/]\.php(/|$)
            {
                try_files $uri =404;
                fastcgi_pass  unix:/tmp/php-cgi.sock;
                fastcgi_index index.php;
                include fastcgi.conf;
            }

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
            {
                expires      30d;
            }

        location ~ .*\.(js|css)?$
            {
                expires      12h;
            }

        access_log  /home/wwwlogs/www.domain.com.log  access;
    }

also return error

I changed permissions but didn't solve the problem
Code:
chown -R www:www /home/wwwroot/ci400rc21

Database Connection Error Handling

$
0
0
Hi,

Is it possible to handle database connection error in CodeIgniter?

I'm loading my database in my core controller using this method

PHP Code:
$this->load->database(); 

I want to handle it when it cannot connect to the specified database, like I want to display the error in json format with my custom error message. Instead of the default error message like below:

PHP Code:
A PHP Error was encountered
Severity
Warning

Message
mysqli::real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using passwordNO)

Filenamemysqli/mysqli_driver.php

Line Number
203 

I will use it with my test REST Api, the reason I want to display the error message in json format.

CodeIgniter 3.1.11
LAMP Stack

Thanks!

Noob Validation Custom Rule Function Quandry

$
0
0
Hello there,
 
I’m a mid-life crisis career-change-wanna-be complete noob programmer (if noob’s the right term here?)- of about a week now- and particularly new to PHP, CI, webservers and suchlike… so apologies upfront for possible and probable stupid questions.
 
I have looked over examples (in CodeIgniter4 4.0.0-rc.2 documentation, and on the CI website– for both CI3 and CI4) and many of the problems/solutions/examples posted on websites like the CI Forum, CI Github, New Myth Media Blog, Stack Overflow etc, though many of them seem to be for CI3, which seems to have some notable differences (?).
 
In my learning process, I have started by trying to simulate user sign in functionality.  I have a Controller, two Views (not shown here, but really simply pages- one a pretty much just single form, and the other one a “blank” success HTML page), a set of custom rules in the Validation.php file, and a CustomRule.php file with the first of the methods that will implement all my custom rules (which, ultimately, I’d like to have all set in the Validation.php file).  For lack of a better idea, I’ve stuck the CustomRules.php file in the app\Config\ folder.
 
There are two parts to my problem:
 
1)  For the life of me, I can’t figure out how to get the Validation service to pass additional parameters (from the form) to my custom rules function called ‘user_validated’.  The CI4 documentation describes what the custom function needs to cater for when accepting additional parameters, but not how to trigger the Validation service to pass these additional parameters to one’s custom function… so although ‘user_validated’ is called, only ‘user_email_offered’ is ever passed as in as a string- nothing else goes in, from what I can tell.  How do I get around this?
 
2) If I manually set the parameter I need (that’s not being passed in the question above), the method runs, but gets stuck with an error saying: “Class 'UserModel' not found - APPPATH/Config\CustomRules.php at line 61”.  I’ve  tried calling with the full path (in line 61, and also using the USE statement above the CustomRules class, both with and without the path to UserModel.php (which is \app\Models\UserModel).  Do I have to put my UserModel.php in the same directory as my CustomRules.php file, or vice-versa?  Ideally, I’d like the models files to remain in the Models\ directory and the CustomRules.php (which, to me is a sub-function of the Validation.php configuration) to remain in the Config\ directory.  Is there a way to achieve this?
 
Extracts from my hack are appended below.
 
I’d be very grateful one of you knowledgeable folk could please point me in the right direction.
 
Thanks.
 
Regards,
Gary
 
 
In app\Controllers\SignupTest.php:
<?php
 
    namespace App\Controllers;
 
    use CodeIgniter\Controller;
 
    class SignupTest extends BaseController
    {
 
            public function index() {   // redirection from the default to signup(), signin(), ...
 
                return $this->signup();
 
            }
 
 
            public function signup() {
                        
                helper(['form']);
 
                $validation = \Config\Services::validation();
                
                if ($this->request->getPost()) {     // still TBD: any different to using $this->request->getGetPost() ?
 
                    $validationResult = $this->validate('user_signin'); // set the rules to use: 'user_signin', 'user_signup'
                    
                    if (!$validationResult) {
 
                        $validationErrors = $validation->getErrors();
 
                        return view('SignupTestView', $validationErrors);   // redisplay simple html form view with list of validation errors
                     
                    } else {
 
                        return view('SignupTestViewSuccess');  // display view to show success
                    }
                } else {
 
                    return view('SignupTestView');   // initial display, in the event of there being no POST data
 
                }
            }
    }
 
   
In \app\Config\CustomRules.php:
<?php

    namespace Config;
   
    use UserModel; // tried adding this to make UserModel visible to the call in uservalidated() method below, also referencing it with use app\Models\UserModel()
 
    //--------------------------------------------------------------------
    // Custom Rule Functions
    //--------------------------------------------------------------------
 
    class CustomRules
    {
       
   
        public function user_validated(string $str, string $fields = NULL, array $data = NULL, string &$error = NULL) : bool{           
 
             $user_email_offered = $str;
             $user_password_offered = '';    // to be extracted using $fields = explode(',', $fields), but $fields is never provided in the call to this user_validated method
            
 
            if (($user_email_offered !== NULL) && ($user_password_offered !== NULL)) {
               
                $usermodel = new UserModel();   // intended to create a UserEntity to permit connectivity to the database, but error thrown is:  Class 'UserModel' not found  or Class 'Config\app\Models\UserModel' not found, if I call it with “new app\Models\UserModel()” 
               
                $user_found = $usermodel->find($user_email_offered);    // we're going to assume that user_email is unique (which is a rule configured in the database table)
             
                if ($user_found === NULL) { // check if user exists before doing the more involved checks in the else-if section below, which may throw exceptions if there's nothing to compare (?)
               
                ...   
    
          }



    }
 
In \app\Config\Validation.php:
?php
    namespace Config;
 
    class Validation
    {
        //--------------------------------------------------------------------
        // Setup
        //--------------------------------------------------------------------
 
        /**
         * Stores the classes that contain the
         * rules that are available.
         *
         * @var array
         */
        public $ruleSets = [
            \CodeIgniter\Validation\Rules::class,
            \CodeIgniter\Validation\FormatRules::class,
            \CodeIgniter\Validation\FileRules::class,
            \CodeIgniter\Validation\CreditCardRules::class,
            \Config\CustomRules::class,
        ];
 
        /**
         * Specifies the views that are used to display the
         * errors.
         *
         * @var array
         */
        public $templates = [
            'list'   => 'CodeIgniter\Validation\Views\list',
            'single' => 'CodeIgniter\Validation\Views\single',
        ];
 
        //--------------------------------------------------------------------
        // Custom Rules
        //--------------------------------------------------------------------
 
        /* configurable limits for validation rules array below*/
        const user_email_min_lenth = 9
        const user_email_max_lenth = 50;
        const user_password_min_lenth = 6;  
        const user_password_max_lenth = 25
 
        
        public $user_signin = [
            'user_email' => [
                'label' => 'e-mail address',
                'rules' => 'trim|required|valid_email|user_validated'// user_validated is custom rule, that will have a custom error message
                'errors' => [
                    'required' => 'You must provide an {field}',
                    'valid_email' => 'Please enter a valid {field}',
                ]
            ],
            'user_password' => [
                'label' => 'password',
                'rules' => 'trim|required',
                'errors' => [
                    'required' => 'Enter a {field} to sign in',
                    'user_password_check' => 'No such user/{field} combination found',
                ]
            ]
        ];
 
 
 

Form generator for CodeIgniter 4

$
0
0
I wrote a library for generating forms in CodeIgniter 4, which works something like the one in the Yii framework.

https://github.com/denis303/codeigniter4-form

Usage:

PHP Code:
$form = new Form($model$errors);

echo 
$form->open();
echo 
$form->inputGroup($data'name', ['id' => 'myinput'], ['label' => 'Custom Label']);
echo 
$form->renderErrors();
echo 
$form->beginButtons();
echo 
$form->submitButton('Submit');
echo 
$form->endButtons();
echo 
$form->close(); 

The library page on the github has a bit more detailed documentation and an example. I will be glad to answer your questions. Also, you can write to me if you need help with your projects on CodeIgniter 4.
Viewing all 14073 articles
Browse latest View live


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