Make a Laravel collection into angular array (octobercms) - angularjs

I managed to fix a problem but I dont understand why it worked and it seems glitchy, so I wonder if someone could explain me. I wanted to get articles from my article models and retrieve that in angular, and I had a hard time getting the subkeys with "featured_images" from octobercms. I found a workaround, like this, in my laravel controller:
public function test()
{
$result = Article::take(4)->get();
$listarr = array();
foreach($result as $article) {
$listarr[] = $article;
foreach($article->featured_images as $image) {
}
}
return response()->json($listarr);
}
But if I remove the foreach($article->featured_images as $image) { } section I dont get the "featured_images" with $listarr. And just using $result doesnt give me those keys if i return response()->json($result);
This is how i want it: http://pastebin.com/MJvnbrrn
But not like this, without "featured_images": http://pastebin.com/1Xa3n9fD
And i get it how i want it if i do that forreach both on $result as $article and only if i then use foreach($article->featured_images as $image) { }. I think I am confused and that there is a more elegant way to this but multidimentional arrays is hard for me.

The foreach call is loading the relationship and therefore including it in the subsequent JSON data. The following call will preload the relationship, using eager loading, and should include it in the same way.
Article::with('featured_images')->take(4)->get();
Alternatively you can use "lazy eager loading"
$result = Article::take(4)->get();
$result->load('featured_images');

Related

Drupal 7 Unable to clear view cache in custom module

I have a view and it is responding fine for the filters I give. However when I run this multiple times in a for loop in my module, I get the same response for whichever filter I apply.
I searched the web and found code to turn off view caching. I have also disabled views data caching from structure->views->settings->advanced. But that is not working.
Below is the example code:
foreach ($term_ids as $term_id) {
$view2 = test_generate_view($view_name, $display_handler, $page, $count, $term_id);
echo "<pre>";
print_r($view2);
}
function test_generate_view($view_name, $display_handler, $page, $count, $term_id = null) {
$view = views_get_view($view_name, TRUE);
$view->set_display($display_handler);
if (!empty($term_id)) {
$term_item = $view->get_item($display_handler, 'filter', 'field_ref_issue_target_id');
$term_item['value']['value'] = $term_id;
$view->set_item($display_handler, 'filter', 'field_ref_issue_target_id', $term_item);
}
$view->init_pager();
$view->pager['items_per_page'] = $count;
$view->pager['use_pager'] = true;
$view->display_handler->options['use_pager'] = true;
$view->set_items_per_page($count);
$view->pager['current_page'] = $page;
$view->is_cacheable = FALSE;
$view->pre_execute();
$view->execute();
return $view;
}
If I don't run them in a loop and try separately for every term-id its working fine. But if I run them in a loop like above, the output is same for any term-id.
The code doesn't look so bad and because the filter changes, the caching should deliver a different result even if turned on. Because the code is working without the loop, maybe you should look into that. is $term_ids really an array of integer values or an array of term objects? If so, the function call would fall back to default which is null for term_ids and would not add a filter.
By the way: You should have a look at contextual filters which you can use really easily.

CakePHP - Declaration of Cart::read() should be compatible with Model::read

And then another message mostly the same saying
Declaration of Cart::save() should be compatible with Model::save
The basic problem is that the cart refuses to update whenever I try to add a product to it(its a simple ajax script).
I wish I could talk more about this but I have no clue whats wrong. I have tried passing different parameters into the function but nothing works. Here are the relevant fucntions, sorry it being long.
CartsController:
$carts = $this->Cart->read();
$products = array();
if (null!=$carts) {
foreach ($carts as $productId => $count) {
$product = $this->Product->read(null,$productId);
$product['Product']['count'] = $count;
$products[]=$product;
}
}
$this->set(compact('products'));
}
public function update() {
if ($this->request->is('post')) {
if (!empty($this->request->data)) {
$cart = array();
foreach ($this->request->data['Cart']['count'] as $index=>$count) {
if ($count>0) {
$productId = $this->request->data['Cart']['product_id'][$index];
$cart[$productId] = $count;
}
}
$this->Cart->save($cart);
}
}
$this->redirect(array('action'=>'view'));
}
Cart Model:
public function save($data) {
return CakeSession::write('cart',$data);
}
/*
* read cart data from session
*/
public function read($data) {
return CakeSession::read('cart', $data);
}
Thanks for any help.
This kind of question has now been asked a felt million times on Stackoverflow. Here is the basic workflow of how to deal with compiler errors and notices that will for sure help you to solve them all on your own:
Read error message
Think about it for a moment
Google for the error message
The error tells you that your method signature must match the inherited parents signature. The arguments must match.
As mark already has mentioned in a comment, overloading the core class methods should only be done if you're pretty sure that you know what you're doing. if not this is very likely ending up in a pile of fail.
You can disable the strict errors but this is really not recommended, they exist for a reason. See How to eliminate php5 Strict standards errors?
Looks like you're doing a cart, well, here is my gift for the CakePHP ecommerce developers: https://github.com/burzum/cakephp-cart-plugin

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

CodeIgniter - List of files and folders using opendir

I'm fairly new to certain programming techniques. Very new to OOP and MVC in general. And I'm pretty sure this is my first StackOverflow question!
I've just downloaded CodeIgniter and have a little project for myself.
I have a list of files and folders on the server and would like to use opendir, readdir and closedir etc to list out them out on a web page in ul's and li's - I've done this in procedural before in a function but have no idea where to even begin with CodeIgniter.
Is there a Helper or Library that already does this? If not, what is the best method? Should I put my code in the model folder?
So confused!
I hope you have learned about MVC architecture already in past year :)
Now about your question. This helper or library you have asked for really exists. For the very same "problem" I have used directory helper and its function directory_map('relative/path/to/your/directory'). This function gets recursively content from your directory and sorts it into array like this
Array
(
[banner] => Array
(
[0] => banner1.jpg
[1] => banner2.jpg
[2] => banner3.jpg
[3] => banner4.jpg
)
[galerie] => Array
(
[0] => 0-PB083393.JPG
[1] => DSCN2897.JPG
[2] => DSCN2908.JPG
[3] => DSCN2917.JPG
[thumb] => Array
(
[0] => 0-PB083393_thumb.JPG
[1] => DSCN2897_thumb.JPG
[2] => DSCN2908_thumb.JPG
)
)
[0] => mapa.jpg
)
which is quite neat and you can use it in - for example - foreach cycle and add ul/li tags.
Probably this question is not relevant after one year, but I hope it could help others.
Ha. This is funny. I was looking for something else and stumbled on to my first ever CI question without realising it was me :D
I've come so far with CI in just less than a month.
I found Directory Helper - directory_map that basically puts your folder structure in to an array of arrays.
I them created a recursive function in the model that turns it in to a proper drop down menu... And when it's a file, it adds in an a href link to that file.
http://ellislab.com/codeigniter/user-guide/helpers/directory_helper.html
If I were doing this, I would:
(1) Create a Library class with a method that takes a directory name and returns an
array of files.
(2) In my controller, I would then load the library and use it to get the list of files for the folder of interest.
(3) I would then load a view while passing the array of file names to the view where
I would assemble the list.
Start by learning how to use the controller to load a view with data (start with a static array). Then learn how to create the library and integrate with your controller.
You might also read up about CodeIgniter's File Helper library unless you want to use the native PHP functions.
Also, learn about PHP unit testing.
I tend to use models for dealing with data from MySQL databases. In your case, you are dealing with information about your file system.
Good luck, CI is a good choice for a PHP/MySQL framework!
First, welcome to CodeIgniter. It rules. Now...
You need a controller function to actually process the directory, similar to this:
public function dir_to_array($dir, $separator = DIRECTORY_SEPARATOR, $paths = 'relative')
{
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value)
{
if (!in_array($value, array(".", "..")))
{
if (is_dir($dir . $separator . $value))
{
$result[$value] = $this->dir_to_array($dir . $separator . $value, $separator, $paths);
}
else
{
if ($paths == 'relative')
{
$result[] = $dir . '/' . $value;
}
elseif ($paths == 'absolute')
{
$result[] = base_url() . $dir . '/' . $value;
}
}
}
}
return $result;
}
Now you need to call that function to return the results, similar to:
$modules['module_files'] = $this->dir_to_array(APPPATH . 'modules');
This will put the results in a variable called $modules, which you can use in whichever way you want, typically put it in a view like this:
$this->load->view('folder/file', $modules);
If you provide an optional third parameter of TRUE to the load->view function, the result of that view will again be returned for you to use anywhere you like, otherwise it will be echoed out where you call it. The view may look something like this:
<?php
if (isset($module_files) && !empty($module_files))
{
$out = '<ul>';
foreach ($module_files as $module_file)
{
if (!is_array($module_file))
{
// the item is not an array, so add it to the list.
$out .= '<li>' . $module_file . '</li>';
}
else
{
// Looping code here, as you're dealing with a multi-level array.
// Either do recursion (see controller function for example) or add another
// foreach here if you know exactly how deep your nested list will be.
}
}
$out .= '</ul>';
echo $out;
}
?>
I have not checked this for syntax errors, but it should work fine. Hope this helps..

How to use find('all') in Views - CakePHP

I searched a lot but I couldn't find on How to use the find('all') in Views as used in Rails, but here I'm getting the error "Undefined property: View::$Menu [APP\Lib\Cake\View\View.php, line 804]"
'Menu' is the model which I'm using to fetch data from the menus table.
I'm using the below code in views:
$this->set('test',$this->Menu->find('all'));
print_r($test);
Inside your Menu model create a method, something like getMenu(). In this method do your find() and get the results you want. Modify the results as you need and like to within the getMenu() method and return the data.
If you need that menu on every page in AppController::beforeFilter() or beforeRender() simply do
$this->set('menu', ClassRegistry::init('Menu')->getMenu());
If you do not need it everywhere you might go better with using requestAction getting the data using this method from the Menus controller that will call getMenu() from the model and return the data. Setting it where you need it would be still better, if you use requestAction you also want to cache it very likely.
TRY TO NOT RETRIEVE DATA WITHIN VIEW FILE. VIOLATION OF MVC RULE
try this in view file:
$menu = ClassRegistry::init('Menu');
pr($menu->find('all'));
In AppHelper ,
Make a below function
function getMenu()
{
App::import('Model', 'Menu');
$this->Menu= &new Menu();
$test = array();
$test = $this->Menu->find('all');
return $test;
}
Use above function in view like :
<?php
$menu = $html->getMenu();
print_r($menu);
?>
Cakephp not allow this .
First create the reference(object) of your model using ClassRegistry::init('Model');
And then call find function from using object
$obj = ClassRegistry::init('Menu');
$test = $obj->find('all');
echo ""; print_r($test); `
This will work.

Resources