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

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

Related

Not getting data from api in cakephp

I am trying to make an api. problem is it does not response value. It shows null. I am using postman. Here I'm keeping json in body with json format. My goal is to show the name when I hit api. Here is data which I am passing
{
"username":"xxxx"
}
In my api controller
public function getName()
{
if ($this->request->is('post')) {
$name = $this->request->data('username');
$val = ["username" => $name];
$this->response->type('json');
$this->response->body(json_encode($val));
return $this->response;
}
}
CakePHP is still PHP. At the very top of the function, I would do a pr($_POST); and see what's coming through. If nothing, are you definitely POSTing? If you do see some data, is it prepended with a model name, or something else, which would cause $this->request->data('username') to return null? At the very least you can make sure you're actually posting to the right place, and go from there.
try this (for CakePHP > 3):
if ($this->request->is('post')) {
$this->viewBuilder()->className('Json');
$name = $this->request->data('username');
$val = ["username" => $name];
$this->set(compact('val'));
$this->set('_serialize', ['val']);
}
Did you try
$input = $this->request->input('json_decode');
pr($input);

Make a Laravel collection into angular array (octobercms)

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');

1146 Table 'Accounting.users' doesn't exist Cake\Database\

I'm working with cakephp3. I want to make login page. Name of table in Accounting database is 'users'.
This is my code:
<?php
namespace App\Controller;
use App\Controller\AppController;
class UsersController extends AppController {
public function login() {
if ($this->request->is('post')) {
$data = $this->request->data;
$cnt = $data->Users->find()
->count();
if ($cnt > 0) {
$this->redirect(['action' => 'index']);
} else {
$this->set('error', 'username or password is incorrct ');
}
}
}}
and this is Users.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class UsersTable extends Table {
}
after login in login page:
Error: Call to a member function find() on a non-object
In your opinion, what is the problem.
$data is not a Table object.
$data = $this->request->data;
$cnt = $data->Users->find()
This is pretty obvious.
I strongly recommend you to take some time and learn about debugging techniques and how to tackle this kind of problem and error messages. A developer should be able to resolve this kind of problem pretty quickly without external help. This is considered normal ever days work for a developer.
1) Read the whole error message 2) Search for it on Google and Stackoverflow, it is very unlikely nobody else ever got that message before. 3) Act according to whatever the cause of the error message is.
In the case of this error message debug what kind of object you're dealing with and figure out why it is not the object you expect it to be. Going trough the call stack helps. Use Xdebugs profiler for that, it's a great tool.
Also don't use variable names like $cnt I assume this is supposed to mean "account" which doesn't even fit into the context it is used. It's very bad named. Instead use proper variable names that are readable and fit into the context. It is a totally wrong assumption that keeping variable names short is any kind of time saver - it is clearly not. The next person working with this will need a dictionary or do a lot of guesswork on what these variables mean.
Instead of $cnt = $data->Users->find()->count(); use $cnt = $this->{$this->modelClass}->find('count');

Undefined variable in view

I am having an issue setting variables in the controller and showing it at the view.
my codes are as follow:
In my view (pages/anything.ctp):
<?php echo $anything; ?>
In my controller (pagesController.php):
public function anything() {
$a = "asdasdas";
$this->set('anything', $a);
}
I am new to Cake, and I've done quite a number of search in google and stack. Still no luck.
I'd be grateful if anybody could help, or if anyone already asked this question before please provide a link that would be best.
First read the following article Controller actions in CakePHP CookBook
When you use controller methods with requestAction(), you will often want to return data that isn’t a string. If you have controller methods that are used for normal web requests + requestAction, you should check the request type before returning:
class RecipesController extends AppController {
public function popular() {
$popular = $this->Recipe->popular();
if (!empty($this->request->params['requested'])) {
return $popular;
}
$this->set('popular', $popular);
}
}
The above controller action is an example of how a method can be used with requestAction() and normal requests. Returning array data to a non-requestAction request will cause errors and should be avoided. See the section on requestAction() for more tips on using requestAction()
Try this:
public function anything() {
$a = "asdasdas";
$this->set(compact('a'));
}
<?php echo $a; ?>

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.

Resources