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

Curlrequest with empty array

$
0
0
Hi,
I'm using the MS Graph API and one of my tasks is to create a new folder on my OneDrive. 
The MS documentation says the message body should be like this:
Code:
{
  "name": "New Folder",
  "folder": { },
  "@microsoft.graph.conflictBehavior": "rename"
}
However I cannot format the folder value to be an empty json array with the curlrequest service.  The request works via postman with an empty json array.
Using the code below, I have tried to state 'folder'=>[], 'folder'=>array, 'folder'=>{},  'folder'=>'{}' and so on
PHP Code:
$client->POST('drives/'.env('msgraph.driveid').'/items/'.env('msgraph.projectfolder.id').'/children',
    [
        'headers' => [
            'Authorization' => $access_token,
            'Content-Type' => 'application/json',
        ], 

        'json'=>[
            'name'=>$MS_Values,
            'folder'=>,
            '@microsoft.graph.conflictBehavior'=>'rename'
         ],
    ],
); 
Foolishly I even tried:

PHP Code:
$empty=[];
$emptyjson_encode($emptyJSON_FORCE_OBJECT);

$client->POST('drives/'.env('msgraph.driveid').'/items/'.env('msgraph.projectfolder.id').'/children',
    [
        'headers' => [
            'Authorization' => $access_token,
            'Content-Type' => 'application/json',
         ], 

         'json'=>[
             'name'=>$MS_Values,
             'folder'=>$empty,
             '@microsoft.graph.conflictBehavior'=>'rename'
         ],
    ],
); 


Any help, is appreciated, this is driving me mad !!!

Hi All,
Eventually I have got this to work.
Code:
$client->POST('drives/'.env('msgraph.driveid').'/items/'.env('msgraph.projectfolder.id').'/children',
    [
        'headers' => [
            'Authorization' => $access_token,
            'Content-Type' => 'application/json',
        ], 

        'json'=>[
            'name'=>$MS_Values,
            'folder'=>['json'=>""],
            '@microsoft.graph.conflictBehavior'=>'rename'
         ],
    ],
); 

Folder place for js,css, img and plugins

$
0
0
Hi,

i'm new on codeigniter4 and i'm not sure how the folder-structure should be.

Where is the right place for
css,js,img etc. for the layout-template
For that i think about public/assets/...

What is the right place for third-party Plugins e.g. Bootstrap, Select2 etc.
For that i think about the same but maybe subfolder.

Is it ok or it there a "must be" place or better place for this parts?

Populating Conditional Lists In Edit View

$
0
0
I have a simple CRUD app. Add and Delete work fine. Having a small problem with the edit view.

The view has several drop down lists where a selection in one changes the contents in a 2nd via an Ajax call which queries a database.

eg  select a country, and a second drop down will get populated with states.

The 2nd drop down is populated via AJAX


When I populate the edit view populating the primary drop down works, and setting the correct selection is fine. However, the Ajax call does not get made, as I assume the change event does not get issued when CI creates the view.

What is the best way to populate the secondary drop down, and restore the value in it from the Model data.

shield problem with sync_permission

$
0
0
hi, to sync permission i created a table permission_list on db with the same value of  AuthGroups.php :
Code:
/**
    * --------------------------------------------------------------------
    * Permissions
    * --------------------------------------------------------------------
    * The available permissions in the system.
    *
    * If a permission is not listed here it cannot be used.
    */
    public array $permissions = [
        'superadmin.manage-admin'      => 'Can manage other admin and user',
        'admin.access'                  => 'Can access the sites admin area',
        'admin.settings'                => 'Can access the main site settings',
        'admin.remove_event_admin'      => 'Can remove all admin event',
        'admin.remove_event_user'      => 'Can remove all user event',
        'admin.manage-admins'          => 'Can manage other admins',
        'admin.manage-users'            => 'Can manage Users',
        'admin.payment-manage'          => 'Can manage payment',
        'user.create-panel'            => 'Can create panel',
        'user.access'                  => 'Can access the sites user area',
        'user.premium_front_end'        => 'Accesso completo lifetime', // 1 [old]
        'user.mountly_front_end'        => 'Accesso completo mensile', // 2 [old]
        'user.pro'                      => 'Funzioni avanzate valido per lifetime/mensile', // 3 [old]
        'user.agency'                  => 'accesso lifetime+PRO con possibilità di rivendita', // 4 [old]
        'user.white_label_100'          => '100 licence di sub-account admin completo', // 5 [old]
        'user.white_label_500'          => '500 licence di sub-account admin completo', // 6 [old]
        'user.new_plan'                => 'Accesso test illimitato', // 7 [old]
       
    ];
then i create a model to get all table's value and in user edit :
Code:
    <div class="row mt-2 mb-2">
     


      <?php foreach($tutti_permessi as $v):?>

        
       
        <div class="col-md-3">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="id_<?=$v->nome  ?>" name="permessi['<?=$v->nome  ?>']" value="<?=$v->nome  ?>" >
            <label class="form-check-label" for="mySwitch"><?=ucfirst(str_replace('_',' ',$v->nome))  ?></label>
          </div>
        </div>
       



      <?php endforeach; ?>

    </div>

in the controller method :
Code:
                ################ GESTIONE PERMESSI #########################

                $string_permessi ='' ;

                foreach($post['permessi'] as $permesso){
               
                    $string_permessi  .=  "'user.".$permesso."'";


                    if (next($post['permessi'])) {
                        //Doesn't Process last element
                        $string_permessi  .= ",";
                    }
                }


                //dd($string_permessi);

                $user->syncPermissions($string_permessi);

                ################ FINE GESTIONE GRUPPO #########################

if i remove a comment of //dd line i have :

Code:
$string_permessi string (40) "'user.premium_front_end','user.new_plan'"
but if i comment dd i have :
Code:
'user.premium_front_end','user.new_plan' is not a valid permission

Why ?

Transaction with multiple models

$
0
0
Hello, this is for a to-do project.
I will insert data into two models, and I want to use a transaction. Where and how should this transaction be managed? I was thinking of doing it in the service layer, but I wanted to ask. If you have any other suggestions, please let me know.

Model Names:
  • tasks (id, title, description, status, created_at, updated_at)
  • task_user (id, user_id, task_id)
Thank you for your time and assistance.

Form Validation - difference between run and validateData

$
0
0
Hi,

i am a little confused as to which method to use.

The little tutorial in the documentation says this->validateData(), but under running validations i see $validation->run(). What is the difference and what should be used? For me they work the same.

period picker recommendation?

$
0
0
Hi everyone,
hope you are doing well?!
I am looking for a nice period picker element. I want a user to filter data by month, quarter or year
Is there anything you have already used and would recommend?

All the best, Jan

Version upgrading - project files - changes list

$
0
0
In user_guide/installation/upgrade_xxx.html
Quote:[url=https://codeigniter.com/user_guide/installation/upgrade_452.html#id2] All Changes

This is a list of all files in the project space that received changes; many will be simple comments or formatting that have no effect on the runtime:


It would be useful to have a list of project files that do have an effect on the runtime, or at least files that have code changes. Especially if one is upgrading for several releases. It would save time and also show that the impact of a release is less onerous than the current all-files-changed list.

At least whoever is doing the upgrade can choose to upgrade just code changes if time is short. And deal with cosmetic changes at another time.

Create a Layout-Template

$
0
0
Hi,

i try to create a layout-template. For that i start with this:

add a template function to the base-controller
Code:
public function template(string $page, array $data)
    {
        //pass this datas to all template files
        $data['view_page']= view($page, $data);
        $data['view_data']= $data;

        //go and create it
        echo view('templates/v1/create_page', $data);
    }


in the central template view "create_page" i want to add/include more additional files, for example 1 file for the header, 1 file for sidenav etc. So i trie this:
Code:
<?= view('templates/v1/view_file_header') ?>
<?= view('templates/v1/view_file_sidebar') ?>
Code:
<div id="header" class="app-header">here content from view_file_header<?= $this->renderSection('header') ?></div>
<div id="header" class="app-header">here content from view_file_sidebar<?= $this->renderSection('sidebar') ?></div>


In my "view_file_header"

Code:
<?= $this->extend('templates/v1/create_page') ?>

<?= $this->section('header') ?>
Put this text from sidebar file
<?= $this->endSection() ?>



In my "view_file_sidebar"

Code:
<?= $this->extend('templates/v1/create_page') ?>

<?= $this->section('sidebar') ?>
Put this text from sidebar file
<?= $this->endSection() ?>



At the end, it doesnt work for me. I recieved a error 500.

Changing the from "view('templates/v1/view_file_sidebar') " to "$this->include('templates/v1/view_file_sidebar')" makes no difference.

What i do wrong?

Windows system support

$
0
0
I would try to adapt all the tests for Windows 11 and a simple PHP 8 installation. It is possible to check for XAMPP after.
But I need feedback from Windows developers and users.
See https://github.com/codeigniter4/CodeIgni...2525260952
To begin with, I have highlighted the tasks for corrections:
1. Is it necessary to do this? I have some time for this.

2. How can we better define the global function


PHP Code:
function _realpath(string $path): string
{
    return str_replace('\\''/'realpath($path));



before calling Boot.php ? While I'm trying to register it in index.php, spark, system/Test/bootstrap.php. They are the first to set up paths

3. Another function


PHP Code:
function normalize_path(string $path): string
{
    return str_replace('\\''/'$path);



is located in system/Common.php. Works with a path-string.

4. Additionally, we no longer need DIRECTORY_SEPARATOR - all paths are given to Unix. Replace with "/". I consider DS useless as long as there are problems with Windows.

If everything works out, we will be able to guarantee work in XAMPP, laragon...

5. Replace all line breaks with "\n". The lines may have different endings if the file was saved in Windows and opened on Unix.
Windows CMD also needs to be rewritten to "\n". Otherwise, there will be errors in the tests

6. There are problems with chmod(), symlink(), vfs:// Should I skip them or issue warnings for phpunit?
7. Several tests can be deleted as they check the differences for Win/Unix.Or do they need to be marked somehow?
8. There are problems with SQLite3 if the database is in :memory:. It doesn't seem to reset when closed or deleted... The data remains in the tables between the tests

In general, there are practically no errors after my changes right now. But for future developments, we need to normalize paths everywhere. I don't know how you feel about this

Possible issue with router->controllerName()

$
0
0
Hi there,
In a filter I'm doing the following:
Code:
  public function before(RequestInterface $request, $arguments = null)
    {
        $router = \Config\Services::router();
        $method = $router->methodName();
        $controllerNameArray = explode("\\", $router->controllerName()); # breaks CI hot reload

This works fine until I turn on "hot reload" whereby I get the following error in the log file:

Code:
CRITICAL - 2024-12-11 12:54:32 --> TypeError: explode(): Argument #2 ($string) must be of type string, Closure given
[Method: GET, Route: __hot-reload]
in APPPATH/Filters/Auth.php on line 35.
1 APPPATH/Filters/Auth.php(35): explode()

It's not critical as I rarely use hot reload, however it could also be me doing something wrong.

Safery request

$
0
0
How can i do use $search - safety?

$builder->where("c.Data->>'$.name' LIKE '%$search%'", null, false);

I have triesd loke this way, but i got SQL error
$builder->like("c.Data->>'$.name'", $search, 'both', false);

{memory_usage}? Is it per visitor, or in total?

$
0
0
Some of my webpages show a {memory_usage} of like almost 100MB... I was wondering if it's cumulative? Like if I get a bunch of traffic to that page, will it crash the site? Or is it 100MB total? Hopefully that makes sense... I'll rewrite it in ChatGPT 4o terms below:
Some of my webpages are showing a {memory_usage} of nearly 100MB. I’m wondering if that memory usage is cumulative—meaning, if the page gets a lot of traffic, could it crash the site? Or is it capped at 100MB total regardless of the number of visitors? I hope that makes sense.

Casting in Entity Classes

$
0
0
Hi,

in my database i have a column with an serialized object.

https://codeigniter4.github.io/userguide...on-casting

Neither json nor array or json-array are working. With array i got an array with the original string as the first element. The documentation says unserialize is used and i expected to unserialze my serialized object. Why is it not working?

Development mode ignored

$
0
0
It seems I've fallen at the first hurdle, I'm trying to follow the initial tutorial here: https://www.codeigniter.com/user_guide/t...index.html
I've set the env file to development, but when I view the public folder, it says Environment: Production on the footer. I have flushed the cache, checked the file on the server and waited a day, but still no difference. It's as if the env file is just being ignored.

How to update with Composer CI not working

$
0
0
Hi

I'm starting to learn How to update with Composer CI not working on the official website.

Instead of asking here every time there is a problem, is it possible to download the pages for the finished app as usual so I can compare my code with the working version? It would be easier for newbies.
Thanks

Using afterFind in Entities?

$
0
0
Hi,

in an old CI 3 version i used a trait in the constructor of a model in order to modify some data. Now in CI 4 i am using entities but in the constructor the data from a database query are not available. Is there a solution i can do that in CI4 Entities?

Problem with sessions, stored in files

$
0
0
I'm having a problem with sessions
I need to store a value in a session so in case user is not logged in. I store this value and after user logs in, I redirect him to the right url etc.

I've made a test controller, associated to 2 routes, to try to debug this problem

Code:
...
public function __construct()
{
  $this->session = \Config\Services::session();
}

public function setCookie($value) {
  $this->session->set('itemId', $value);
  echo "Done";
}

public function getCookie() {
  $userData = $this->session->get();
  $logged = $this->session->get('logged_in');
  $itemId = $this->session->get('itemId');
  echo "<pre>";
  echo "userData:<br/>"; print_r($userData); echo "<br/>";
  echo "logged:<br/>"; print_r($logged); echo "<br/>";
  echo "itemId:<br/>"; print_r($itemId); echo "<br/>";
  echo "</pre>";
}

Then I do some test in my PC
http://localhost/myapp/setcookie/25
and then
http://localhost/myapp/getcookie

All works fine, but when I do the same test on server

https://sub.domain.com/setcookie/25
and then
http://sub.domain.com/getcookie

The output I get is:

userData:
Array
(
    [__ci_last_regenerate] => 1734363353
    [_ci_previous_url] => https://sub.domain.com/setcookie/25
)

logged:
NULL

itemId:


The weird thing is that I can see the itemId being stored in the session file (writable/session) on server, after calling setcookie/25

How can I make this work or debug deeper to find out what's wrong ?

PS: writable/session has the 777 chmod, and www-data:www-data ownership, etc.

Governance

$
0
0
Hi, I was looking around the website and noticed CodeIgniter is owned by a Foundation, which is great, but there is no listing of the current Board or any meeting minutes.
I found a 2019 thread listing 3 directors but after 5 years I didn't have a lot of confidence that information was accurate.
Who are the current Board members? Has there been any Board meetings in 2024 or financial reports?
With the latest WordPress governance issues, I'm looking to vet my dependencies for their governance structures, and I think it'd be great if there was more information about this on the CodeIgniter website. I actually think this is as important as technical documentation at this point, because I want to invest in a system that is sustainable, not maximizing profitability for its shareholders.
Thanks!

Codeigniter 4 custom log levels

$
0
0
Hi, I've been looking for information regarding extending CI 4 logger to customize log levels, file path, filename, etc.
I read about extending FileHandler, but it is a bit over my head. 
So far, I was able to achieve adding custom log levels using file handler and an extended Logger class.

Currently working with CodeIgniter 4.5.5. Here is the code for anyone interested in similar functionality.

app/Log/AuditLogger.php
PHP Code:
<?php
namespace App\Log;

use 
CodeIgniter\Log\Logger as BaseLogger;

class 
AuditLogger extends BaseLogger {

    
    
public function __construct($configbool $debug CI_DEBUG)
    {
        parent::__construct($config$debug);

        $this->logLevels = [
            ...$this->logLevels,
            'audit' => 9
        
];

        $this->loggableLevels is_array($config->threshold) ? $config->threshold range(1, (int) $config->threshold);

        // Now convert loggable levels to strings.
        // We only use numbers to make the threshold setting convenient for users.
        if ($this->loggableLevels !== []) {
            $temp = [];

            foreach ($this->loggableLevels as $level) {
                $temp[] = array_search((int) $level$this->logLevelstrue);
            }

            $this->loggableLevels $temp;
            unset($temp);
        }
    }




app/Config/Services.php
PHP Code:
namespace Config;

+
  use App\Log\AuditLogger;
+
  use Config\Logger as LoggerConfig;
    use CodeIgniter\Config\BaseService;

...

 public static function 
logger(bool $getShared true)
    {
        if ($getShared) {
            return static::getSharedInstance('logger');
        }
 
        return new AuditLogger(config(LoggerConfig::class));
    


app/Config/Logger.php
PHP Code:
<?php
...
    * - Debug Detailed debug information.
-
   * - All Messages
  * - Audit entity registration and update logging (user actions)
  * - 10 All Messages

...

-
  public $threshold = (ENVIRONMENT === 'production') ? 49;
+
  public $threshold = (ENVIRONMENT === 'production') ? 410;

...

 
FileHandler::class => [
            // The log levels that this handler will handle.
            'handles' => [
                'critical',
                'alert',
                'emergency',
                'debug',
                'error',
                'info',
                'notice',
                'warning',
+
               'audit'
            ], 

Now you can use the custom log level in your code:
PHP Code:
log_message('audit'$msg); 

Log file:
PHP Code:
...
INFO 2024-12-16 09:53:41 --> CSRF token verified.
AUDIT 2024-12-16 09:53:54 --> [CLIENT REGISTERby [adminID 9 username =  -> Tomasemail =  -> xxx@xxxxx.xxxcompany_name =  -> XXXXXcompany_ctry_id =  -> 28
INFO 
2024-12-16 09:53:55 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
... 

If anyone knows how to extend logger to customize filename and location, any information is appreciated.
Viewing all 14343 articles
Browse latest View live


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