Code Igniter: Access array elements from controller - arrays

I have written this function in CI and for various reasons, I need to assign the contents of the array to variables to use later in the controller.
Because of the way this legacy code is set up, I need to get to the elements of the array from the controller. How do I get to the array elements in $data['oneResult'] from function below. I have tried a few things like the element() helper. Nothing works. In debug mode, I see the data I need and at this point, I need to assign so I want to do this:
$holdID = $data['oneResult']['contact_id'];
$holdLoc = $data['oneResult']['location']; etc.
public function getOneValue(){
$this->load->model('get_contents');
$data['oneResult'] = $this->get_contents->getSpecificRow();
$data['title'] = 'One Record - Contacts table view';
$this->load->view('contacts_view', $data);
}
I am testing this in CI 2, but will need it to work in CI 1.7
Can anyone show me how to do this please?

make a global variablw and assign the data to it..
class something extend CI_controller{
var $holdID ='';
var $holdLoc = ''; etc.
public function __construct() {
....
}
public function index(){
...
}
public function getOneValue(){
$this->load->model('get_contents');
$data['oneResult'] = $this->get_contents->getSpecificRow();
$this->holdID = $data['oneResult']['contact_id']; //<----here assing value to global var
$this->holdLoc = $data['oneResult']['location']; //<--here
$data['title'] = 'One Record - Contacts table view';
$this->load->view('contacts_view', $data);
}
}

I suppose you want the data to be available the next time you are visiting the controller.
In that case, global variables won't hold the value because of the architecture and functioning of codeigniter.
Here are possible ways, that i can suggest:
1) declare session variables and use.(not a very efficient one)
2) declare variable in config file.(preferred and might just do the trick for you).
If either of the above two does not resolve your issue, elaborate a little on your use-case.
Will give it a fresh attempt.
-- seekers01

Related

Determining the movieclip assigned to a variable in an array AS3

Please forgive my terminology, Im not educated on the proper.
Lets say I have multiple movieclip variables
var rblock1:MovieClip = new Rblock();
var rblock2:MovieClip = new Rblock();
var rblock3:MovieClip = new Rblock();
var yblock1:MovieClip = new Yblock();
var yblock2:MovieClip = new Yblock();
var yblock3:MovieClip = new Yblock();
I have them added to an array
var blockarray:Array = new Array(rblock1, rblock2, rblock3, yblock1, yblock2, yblock3);
var block
I want to create a for loop with an if statement that triggers if a variable is Rblock and not Yblock, for example
for each (block in blockarray)
{
if (block==Rblock)
{
trace("rblock");
}
}
The issue is that obviously "if (block==Rblock)" doesnt work.
How should this be written?
You apparently want to check if a block is red or yellow by checking against its class name. You can do it with this:
if (block is Rblock) {...} // yes, red
I have figured out a work around not really a perfect solution, which will only work for certain scenarios...
if each class has a unique trait you can identify it that way, for example...
if all variables defined by the Rblock class are wider than the Yblock class you could say
if (block.width>x) { trace(Rblock); }
Like I said this is only a work around though and only works for movieclip variables defined by classes that are different, if anyone has the actual solution please post

Referencing a Struct not using the variable's name

Hello I have a swift file that contains arrays of tuples that I reference with my app. For example, my structure looks like:
struct workoutDict {
static var bicepWorkouts = [("Barbell Curl","Bicep",0,"3x10"), ("x","x",3,"x")]
}
I have a global variable named eqID. For example, eqID = "bicepWorkouts"
There is part of my code where I attempt to call this dictionary. Normally I would use: workoutDict.bicepWorkouts and this works fine, but I have other workouts such as barbellWorkouts in my dictionary so i let the user select "bicepWorkouts", "barbellWorkouts" ect based on user input and need to use that to reference my struct.
Right now i have
//Call the global variable to get what workout to look for
code = eqID
let ourWorkouts = workoutDict.code
which should set ourWorkouts = workoutDict.bicepWorkouts when our eqID is set to that, but it keeps giving me the error that workoutDict does not contain the code when I use that reference.
I tried researching alternate methods of referencing structs but I couldn't find anything. Any help would be appreciated!
You should create yet another dictionary to store the names:
struct workoutDict {
static var dicts = [ "bicepWorkouts": bicepWorkouts, "barbellWorkouts": barbellWorkouts ]
}
Then you can access the sub dictionaries by:
workoutDict.dicts[eqlID]

IndexedDb dynamically populating existing ObjectStores

I have created many, let's say three ObjectStores inside a defined and versioned IndexedDB schema.
I need to populate all of them. To do so, I created an object which stores both name end endpoint (where it gets data to populate).
Also to avoid error when trying to fill objectstores already populated, I use the count() method to ... count key inside the objectstore and if there are 0 key, then populates, else reads.
It works perfect if I execute on a one by one basis, that is instead of using a loop, declare and execute each one of the three objectstores.
However when invoking the function to populate each storage inside a loop, I get the following error message for the last two objectstores to be populated:
Failed to read the 'result' property from 'IDBRequest': The request
has not finished. at IDBRequest.counts.(anonymous function).onsuccess
Here is the code:
// object contains oject stores and endpoints.
const stores = [
{osName:'user-1', osEndPoint:'/api/1,
{osName:'user-2', osEndPoint:'/api/2},
{osName:'user-3', osEndPoint:'/api/3}
];
// open db.
var request = indexedDB.open(DB_NAME, DB_VERSION);
// in order to dynamically create vars, instantiate two arrays.
var tx = [];
var counts = [];
var total = [];
// onsuccess callback.
request.onsuccess = function (e) {
db = this.result;
for(k in stores) {
tx[k] = db.transaction(stores[k].osName).objectStore(stores[k].osName);
counts[k] = tx[i].count();
counts[k].onsuccess = function(e) {
total[k] = e.target.result;
// if the counting result equals 0, then populate by calling a function that does so.
if (total[k] == 0) {
fetchGet2(stores[k].osEndPoint, popTable, stores[k].osName); //
} else {
readData(DB_NAME, DB_VERSION, stores[0].osName);
}
};
} // closes for loop
}; // closes request.onsuccess.
The fetchGet2 function works well inside a loop, for example the loop used to create the objectstores, and also has been tested on a one by one basis.
It looks like an async issue, however I cannot figure how to fix the problem which is to be able to populate existing objectstores dynamically, avoiding to populate filled objectsores and only filling empty ones.
Indeed testing without the count issue, but inside the loop works perfect, or with the count but without loop.
At the moment and when logging counts[k], It only logs data for the last member of the object.
Thanks in advance, I'm coding with vanilla js, and I'm not interested in using any framework at all.
Yes, this looks like an issue with async. For loops iterate synchronously. Try writing a loop that does not advance i until each request completes.

Using Active Record pattern in CakePHP, and avoiding passing arrays around

As my CakePHP 2.4 app gets bigger, I'm noticing I'm passing a lot of arrays around in the model layer. Cake has kinda led me down this path because it returns arrays, not objects, from it's find calls. But more and more, it feels like terrible practice.
For example, in my Job model, I've got a method like this:
public function durationInSeconds($job) {
return $job['Job']['estimated_hours'] * 3600; // convert to seconds
}
Where as I imagine that using active record patter, it should look more like this:
public function durationInSeconds() {
return $this->data['Job']['estimated_hours'] * 3600; // convert to seconds
}
(ie, take no parameter, and assume the current instance represents the Job you want to work with)
Is that second way better?
And if so, how do I use it when, for example, I'm looping through the results of a find('all') call? Cake returns an array - do I loop through that array and do a read for every single row? (seems a waste to re-fetch the info from the database)
Or should I implement a kind of setActiveRecord method that emulates read, like this:
function setActiveRecord($row){
$this->id = $row['Job']['id'];
$this->dtaa = $row;
}
Or is there a better way?
EDIT: The durationInSeconds method was just a simplest possible example. I know for that particular case, I could use virtual fields. But in other cases I've got methods that are somewhat complex, where virtual fields won't do.
The best solution depends on the issue you need to solve. But if you have to make a call to a function for each result row, perhaps it is necessary to redesign the query taking all the necessary data.
In this case that you have shown, you can use simply a virtual Field on Job model:
$this->virtualFields = array(
'duration_in_seconds' => 'Job.estimated_hours * 3600',
):
..and/or you can use a method like this:
public function durationInSeconds($id = null) {
if (!empty($id)) {
$this->id = $id;
}
return $this->field('estimated_hours') * 3600; // convert to seconds
}

cakePHP get a variable from each Model and Controller

I got a question. I have a db table with settings (id, name).
If I read them from the db
$settings = $this->Setting->find('list');
How can I do this in the AppController or something like that to access from each Controller and Model?
Hope someone can help me.
Thanks
Explanation:
I would assume you're looking for something like below (Obviously you'll want to tweak it per your own application, but - it's the idea).
In the app controller, it
finds the settings from the table
repeats through each and puts each one into a "Configure" variable
Code:
/**
* Read settings from DB and populate them in constants
*/
function fetchSettings(){
$this->loadModel('Setting');
$settings = $this->Setting->findAll();
foreach($settings as $settingsData) {
$value = $settingsData['Setting']['default_value'];
//note: can't check for !empty because some values are 0 (zero)
if(isset($settingsData['Setting']['value'])
&& $settingsData['Setting']['value'] !== null
&& $settingsData['Setting']['value'] !== '') {
$value = $settingsData['Setting']['value'];
}
Configure::write($settingsData['Setting']['key'], $value);
}
}
Then, you can access them anywhere in your app via Configure::read('myVar');
A warning from the CakePHP book about Configure variables. (I think they're fine to use in this case, but - something to keep in mind):
CakePHP’s Configure class can be used to store and retrieve
application or runtime specific values. Be careful, this class allows
you to store anything in it, then use it in any other part of your
code: a sure temptation to break the MVC pattern CakePHP was designed
for. The main goal of Configure class is to keep centralized variables
that can be shared between many objects. Remember to try to live by
“convention over configuration” and you won’t end up breaking the MVC
structure we’ve set in place.

Resources