Add the array to the $data variable before passing it to the views

Currently, I am using CI and I have a specific method to load a CSS file in the constructor for every main page (e.g. contents) like this:

$this->load->vars(array('add_css'=>array('contents')));

In my views, I check if the add_css array exists, and if it does, I load the contents.css file. However, in my controller file (specifically contents.php), there are numerous methods, all of which will always load the additional contents.css file. Some methods may also require their own separate CSS files. For instance, when on the review method, I want to load an additional rating.css file. Here is what I tried:

$data['add_css'] = array('rating');

Unfortunately, this approach doesn't work as the rating.css file overwrites the variables set in the constructor.

Is there a way for me to push the array instead? I attempted to use `array_push($data['add_css'],'rating')`, but it did not yield the desired results.

Thank you!

Answer №1

To achieve a more sophisticated solution, consider the following approach:
1. Start by adding a new protected property in your controller (or MY_Controller) to store all loaded CSS files.

protected $_addCss = array();

2. Create a method for adding new CSS files to this array:

protected function _addCssFile($file)
{
    $this->_addCss[] = $file;
    return $this; //Allows for chaining when adding files
}

3. Implement a method for manually loading all added CSS files.

protected function _loadCssFiles()
{
        //Load the variables and then reset the property to an empty array
    $this->load->vars(array('add_css' => $this->_addCss));
    $this->_addCss = array();
    return $this;
}

4. Utilize this functionality in your application controller as follows:

public function __construct()
{
        parent::__construct();
        $this->_addCssFile('contents');
}

public function test()
{
        //Chain the methods to add multiple CSS files
    $this->_addCssFile('contents')
        ->_addCssFile('rating')
        ->_loadCssFiles()
        ->load->view('test');
}

5. In your view:

echo '<pre>';
print_r($add_css);
echo '</pre>';
Result:
Array
(
    [0] => contents
    [1] => contents
    [2] => rating
)

Answer №2

Encountered a comparable issue. Review the contents of the array, transfer to a separate array, append fresh data to it, and replace the second array with the updated information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating multiple rows in Laravel using input data

Check out the app here I recently created a multi-row update feature with JavaScript. The button function successfully retrieves the ID of each row, but now I'm facing a challenge. I want to include an input form for the data that is being updated. ...

PHP Quick Tip: How to effortlessly update a JSON array with new data

{ "messages": [ { "sender": "x", "message": "Placeholder", "date": "May 8, 2016 11:47:45 PM" } { "sender": "y", "mess ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

Validation of default values in contact forms

Obtained a free contact form online and hoping it works flawlessly, but struggling with validation for fields like "Full Name" in JS and PHP. Here is the HTML code: <input type="text" name="contactname" id="contactname" class="required" role="inpu ...

Discovering and Monitoring Viruses on a WordPress Website

My dedicated server is set up with WHM/cPanel CentOS Apache. One of the accounts on cPanel is hosting a WordPress site that has been infected with a virus. This virus is being used to send emails and inject affiliate links without authorization. Despite ...

Uploading pictures to a directory and storing their filenames in a database with the help of PHP

I'm facing a challenge trying to upload 2 files into a folder and save their names and image paths in a database. Below is my HTML code for reference: <input class="field2" type="file" name="file[]" multiple="multiple" /> Here is the PHP code ...

Look up and access the file

My latest script is designed to search for a specific file in the current directory. If it doesn't find the file, it will move up one directory and try again. The script functions properly when the file is found. However, if the file is not present, ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

Investigating the Netbeans PHP Xdebug Socket Exception while debugging Joomla

System Information PHP Version 5.4.0-1build1~ppa1~oneiric Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans Apache/2.2.20 (Ubuntu) While debugging a Joomla project, I encounter a Socket Exception error right before reaching the spot where the ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

Navigating through the outputs from a MySQL query

There is a specific functionality I am trying to achieve, although I may not have the exact terms to describe it. Let me explain what I need in detail. Initially, there is a variable named $id, which essentially represents $_GET['id']. For insta ...

Challenges with Dependency Injection in Symfony 4.1 Components

Currently, I am in the process of updating an older PHP application. I am attempting to utilize Symfony's dependency injection component to inject services into controllers (and other services), but I am encountering difficulties as the Symfony docum ...

Updating the table in real time with new data from the MySQL database without the need to

I'm struggling with dynamically adding new lines to my table without refreshing the page. Most of the guides I've found suggest using Ajax, but that resets my table. My table displays a name, status, and message fetched from the database. The use ...

Database-driven menu selection

I am currently working on creating a dynamic side navigation menu that pulls its content from a database. The goal is to have the main categories displayed on the left-hand side, and when one is clicked, the others will slide down to make room for any subc ...

`Explore SQL data using modal window`

Hey there, I'm in a bit of a pickle with my code. As someone who's just dipping their toes into the world of AJAX and has a vague understanding of PHP, I find myself lost in trying to figure out where things went wrong. My challenge lies in fetc ...

reorganize php array structure

I currently have an array that looks like this: Array ( [1] => Vice President [3] => Secretary [5] => Treasurer ) My goal is to transform it into this format: Array ( [0] => Vice President [1] => Secretary [2] => Treasurer ) I attempt ...

Deciphering the JSON structure of GoogleMaps Directions API

Looking to utilize the Google Maps API direction JSON Object? Check it out here In order to display instructions as a user reaches a location, I need to access the "STEPS" JSON Array. This array contains startLocation and endLocation objects. I have the ...

Querying objects using a PHP API

Currently facing an issue with the API documentation I'm working on. Despite testing the code, it simply isn't functioning as expected. After spending a considerable amount of time analyzing it, I seem to be at a loss in figuring out where the er ...

Working with dynamic array sizes in methods and setters in PHP

I am relatively new to PHP and have been researching extensively, but I am struggling to find a solution to my current issue. My problem revolves around using setters in a class when dealing with an array of unknown size. For example: class Shirt { ...

Saving a user's geographic location in a database: Steps to success

Is there a way to save Google Maps data into a MySQL database using PHP? I'm trying to create a system that captures the latitude and longitude of users when they visit my website. I am utilizing the Google Maps API for this purpose, but I'm unsu ...