CakePHP Component not working - cakephp

Hey guys, I'm working on a cakephp app that manages a list of alpha users. It's a simple form that accepts a name and email and then generates an alpha code after submission, that alpha code is then stored in the record with the name and email under the column "code." I'm using a component calleed PasswordHelper which is located here
Here' my code
class AlphaUsersController extends AppController {
var $name = 'AlphaUsers';
var $components = array('PasswordHelper');
function add() {
if(!empty($this->data)) {
if($this->AlphaUser->save($this->data)){
$this->AlphaUser->set('code', generatePassword(10));
$this->AlphaUser->save();
$this->Session->setFlash('User has been added.');
$this->redirect(array('action' => 'index'));
}
}
}
}
The form data saves just fine when I don't include the alpha code lines, but when I try to generate the password, I get this error.
Fatal error: Call to undefined function generatepassword() in /Users/Warren/Sites/caroverload/app/controllers/alpha_users_controller.php on line 22
What's going on here? I have the PasswordHelper file saved in the appropriate components directory and it's added in the components array for this controller.

I think the way you are calling the PasswordHelper methods should look more like this: $this->PasswordHelper->generatePassword(10).
As you have it now, it is looking for that as a global function, which doesn't exist and throws the error.

Related

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; ?>

how to reach database fields from default.ctp in Cakephp

I'm unable to show a db field value in default.ctp , like unreaded messages or username ,
I keep getting Undefined variable: user, or message
how to reach them from default.ctp ?
Since your default layout is application wide, you will need to process data in the AppController.php in the beforeFilter method, so something like this
In AppController.php :
public function beforeFilter() {
//for example, you want to read messages
//import the Model
$this->loadModel('Message');
$all_messages = $this->Message->find('all'); //or whatever you need to do to get the data
$this->set('all_messages', $all_messages);
}
Then in your default.ctp,call the variable: $all_messages

CakePHP3.x custom validation not working

Inside UsersTable class, I am trying to implement custom validation following the CakeBook but I got an error saying, Object of class App\Model\Table\UsersTable could not be converted to string [CORE/src/Validation/ValidationRule.php, line 128]. Below is my code in UsersTable.php.
class UsersTable extends Table{
public function validationDefault(Validator $validator){
$validator->add(
"password",[
"notEmpty"=>[
"notEmpty"
],
"custom"=>[
"rule"=>[$this,"customFunction"],
"message"=>"foo"
]
]
);
}
public function customFunction($value,$context){
//some logic here
}
}
Looking at ValidationRule.php in core CakePHP library, I have noticed that array_shift() (on line 185) is taking the first element of [$this,"customFunction"], that is, $this and assigning it to $value. But actually $value should be [$this,"customFunction"]. Therefore, for my code to work without any error, I needed to add one more nesting to [$this,"customFunction"](So it is now [[$this,"customFunction"]]). Do I misunderstand something or is this some kind of bug?
UPD: This problem is now fixed.
I think you've spotted that correctly, the problem seems to be that CakePHP expects the rule key value to be in
[string or callable, ...args]
format when it is in array, ie it doesn't test whether the value itself already is a callable.
The documentation says that the non-nested variant should work, so you might want to report this as a bug.
Use this in your model for custom validation
public function validationCustom($validator)
{
return $validator
->notEmpty('username', 'A username is required');
}
Use validation method name except validation keyword in your controller when you want to save or update
$user = $this->Articles->newEntity($this->request->data,
['validate' => 'custom']);

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