Error: userHelper could not be found in cakephp3.5.1 - cakephp

How to fix this issue
Error: userHelper could not be found.
this is my search.ctp inside element which is called in default.ctp
<?php echo $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'search']], array('type' => 'get')); ?>
<?php echo $this->Form->input('username'); ?>
<?php echo $this->Form->button('Search', ['type' => 'submit']); ?>
Below is my search controller
public function search() {
$value = $this->request->getData('username');
$results = $this->Users->find('all', ['fields'=>[
'Users.username',
'Users.email',
'Users.id',
'Users.age',
'Users.address',
'Users.gender'
],
'order' => 'Users.id ASC',
'conditions' => array(' username LIKE' => "%".$value."%")
]);
$this->set('user', $results);
$this->set('_serialize', ['user']);
}
search.ctp inside users
<?php
use Cake\ORM\TableRegistry;
use Cake\Filesystem\Folder;
use App\Controller\AppController;
?>
<?php foreach ($user as $users): ?>
<?php echo $this->users->username;?>
<?php endforeach;?>

What is the line inside loop? It shouldn't be.
$this->users->username;
I'm not so sure returning as a array or object in cakephp 3.
But, I'm sure that it should be like that,
$users->username;
or
$users['username'];

Related

How to merge two forms with two different models in one form in CakePHP 3.5?

I am a beginner of CakePHP and I'm using version 3.5. I really get confused by it. My problem is I want to merge two forms from 2 different models. In my case, I want to merge the client transaction add form and service detail add form all in one form. Here are my codes below:
add.ctp (I merge the add client transaction form in service detail add form)
<div class="serviceDetail form large-9 medium-8 columns content">
<?= $this->Form->create($clientTransaction) ?>
<fieldset>
<legend><?= __('Add Client Transaction') ?></legend>
<?php
echo $this->Form->control($serviceDetail->client_transaction->client->id, ['options' => $clients]);
echo $this->Form->control($serviceDetail->client_transaction->client->transaction_date, ['timeFormat' => 12, 'disabled' => false]);
echo $this->Form->control($serviceDetail->client_transaction->client->status, ['type' => 'hidden', 'value' => 0]);
?>
</fieldset>
<?= $this->Form->create($serviceDetail) ?>
<fieldset>
<legend><?= __('Add Service Detail') ?></legend>
<?php
echo $this->Form->control('service_id', ['options' => $service, 'empty' => true]);
echo $this->Form->control('user_id', ['options' => $users, 'empty' => true, 'label'=> ['text' => 'Barber']]);
echo $this->Form->control('client_transaction_id', ['options' => $clientTransaction, 'empty' => true]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
in my service_detail controller
public function add()
{
$this->paginate = [
'contain' => ['Service', 'Users', 'ClientTransaction']
];
$clientTransaction = $this->ServiceDetail->ClientTransaction->newEntity();
$serviceDetail = $this->ServiceDetail->newEntity();
if ($this->request->is('post')) {
$clientTransaction = $this->ServiceDetail->ClientTransaction->patchEntity($clientTransaction, $this->request->getData());
$serviceDetail = $this->ServiceDetail->patchEntity($serviceDetail, $this->request->getData());
if ($this->ServiceDetail->ClientTransaction->save($clientTransaction) && $this->ServiceDetail->save($serviceDetail)) {
$this->Flash->success(__('The transaction has been added.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Please, try again.'));
}
$service = $this->ServiceDetail->Service->find('list', ['limit' => 200]);
$users = $this->ServiceDetail->Users->find('list',['limit' => 200, 'valueField' => 'first_name'])->where(['position' => 2]);
$clientTransaction = $this->ServiceDetail->ClientTransaction->find('list', ['limit' => 200]);
$clients = $this->ServiceDetail->ClientTransaction->Clients->find('list', ['limit' => 200]);
$serviceDetail = $this->paginate($this->ServiceDetail);
$this->set(compact('serviceDetail', 'service', 'users', 'clientTransaction'));
}
Do something like this:
$serviceDetail = $this->ServiceDetail->newEntity(
$this->request->getData(), [
'associated' => ['ClientTransaction']
]
);
https://book.cakephp.org/3.0/en/orm/saving-data.html#converting-request-data-into-entities
For your page follow this pattern:
https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data

How to pass param in url using cakephp

I am using cakephp 2.6.7. I want to pass param in url. My expected url is: http://demo.jegeachi.com/tolets/search?page=2
but url is look like:
http://demo.jegeachi.com/tolets/search/%2526page%253D2
My code is:
if ($total_page > 2):
$current_page = 0;
if(isset($this->params['url']['page'])){
$current_page = $this->params['url']['page'];
}
?>
<?php if($current_page>1){
$url = 'page='.--$current_page;
?>
<li> «</li>
<?php }?>
<?php for ($page = 1; $page <= $total_page; $page++):
?>
<?php if ($page == $current_page) { ?>
<li><span><?php echo $page; ?> </span></li>
<?php } else {
$url = '&page='.$page;
?>
<li><?php echo $page; ?></li>
<?php } ?>
<?php endfor;
?>
<?php if($current_page<$total_page){
$url = 'page='.++$current_page;
?>
<li>»</li>
<?php } ?>
<?php endif;
?>
I also tried to use urlencode but no luck.
also you can use
<?php
echo $this->Html->link('Title', array(
'controller' => 'tolets',
'action' => 'search','?page=2')
);
?>
If this is a view code
<?php
echo $this->Html->link('Title', array(
'controller' => 'tolets',
'action' => 'search',
'?' => array('page' => 2))
);
?>
It will output
Title

CakePHP-3.0 plugin form validation error message and entered data

I have created a CommentManager plugin for adding comments in my posts. Adding the comment form in Posts/view.ctp file and the comment form action is redirecting to CommentManager/Comments/add.
The comments are saving properly but when saving empty form, that doesn't shows the validation error messages which i have written in CommentsTable and also the entered data has gone from the form.
CommentManager/src/Controller/CommentsController/add
public function add()
{
$ccomment = $this->Comments->newEntity($this->request->data);
if ($this->request->is('post')) {
$newData = ['post_id' => $this->request->params['pass'][0]];
$ccomment = $this->Comments->patchEntity($ccomment, $newData);
if ($this->Comments->save($ccomment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$this->set(compact('ccomment'));
return $this->redirect($_SERVER['HTTP_REFERER']);
}
CommentManager/src/Model/Table/CommentsTable
public function validationDefault(Validator $validator) {
return $validator
->notEmpty('body', 'Body contents required.')
->notEmpty('email', 'An email is required.')
->add('email', [
'format' => [
'rule' => [
'custom',
'/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
],
'message' => 'Enter a valid email.'
]
]);
}
src/Template/Posts/view.ctp
<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>
<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
<p><?php echo $comment->body; ?></p>
<?php } ?>
<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>
Don't call newEntity() with an empty array. Inste of
$ccomment = $this->Comments->newEntity($this->request->data);
Do:
$ccomment = $this->Comments->newEntity();
And in in the call to patchEntity() pass the $this->request->data

cakephp szajbus uploadpack - image doesn't show because self::$__settings array is empty

I have 2 views, postview.ctp and usercomment.ctp, calling the same comment.ctp element. This element shows image using UploadPack helper. But image on usercomment.ctp doesn't show and has this error message
Notice (8): Undefined index: User [APP\Plugin\upload_pack\Model\Behavior\UploadBehavior.php, line 222]
line 222: $settings = self::$__settings[$modelName][$field];
The self::$__settings in usercomment.ctp is empty , but in postview.ctp it's not empty and the image showed up correctly.
comment.ctp:
<?php echo $this->Html->link($this->upload->image(
$comment['User'],
'User.avatar',
array('style' => 'thumb'),
array('class' => array('img-responsive', 'img-rounded'))
),
array('controller' => 'users',
'action' => 'view',
$comment['User']['id']),
array('escape' => false)
) ?>
And this is code to call comment.ctp on from the both view.
<?php if (!empty($comments)): ?>
<?php foreach ($comments as $comment): ?>
<?php echo $this->element('comment',array('comment' => $comment));?>
<?php endforeach; ?>
<?php endif; ?>
I've checked the $comment array and they're identical. How to fix it?
Load User model on usercomment action in Comment controller.
public function usercomments($id) {
$this->loadModel('User');
if($this->Auth->loggedIn()){
.....

cakephp: how to render related models in the view

My objective is to display records for a related child model (once removed) in the view. My problem is that I receive a 'Notice (8): Undefined index:' error message when I try to output the following query.
Tournaments have many tournamentDetails, and tournamentDetails have many updates. I'm trying to display all the updates for each tournamentDetail that is displayed on the tournaments view.
So my question is how to properly resolve the error message and display the updates for each tournamentDetail on the tournaments view page.
My find data in the 'tournaments' controller view action is:
$updates = $this->Tournament->TournamentDetail->Update->find('all', array( 'tournament_details.tournament_id'=> $this->data['Tournament']['id']));
In the view, I have this code.
<?php foreach ($tournament['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
This is the same 'foreach' code the I use for the other related child records without problem. I did use the debug() function to investigate but didn't see what I was missing.
The output of the $updates array from the debug function looks like this:
Array
(
[0] => Array
(
[Update] => Array
(
[id] => 1
[title] => first round matches start today
[date] => 2010-03-19
[body] => this tournament's first round matches start today.
[tournament_detail_id] => 4
[homeStatus] => no
)
Is there a special way to display records this deep?
As always, thanks in advance.
Paul
Update: Feb 23/11
After some testing the problem I seem to have is finding and passing the correct value to the $updates variable;
To summarize, I want the $updates variable to hold the current 'tournament_details_id'. This will then display the related update records in the 'tournaments' view.
I'm still a beginner and most likely overlooked the obvious.
Here is the model info:
class Tournament extends AppModel {
var $name = 'Tournament';
var $hasMany = array(
'TournamentDetail' => array(
'className' => 'TournamentDetail',
'foreignKey' => 'tournament_id',)
class TournamentDetail extends AppModel {
var $name = 'TournamentDetail';
var $belongsTo = array(
'Tournament' => array(
'className' => 'Tournament',
'foreignKey' => 'tournament_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
class Update extends AppModel {
var $name = 'Update';
var $belongsTo = array(
'TournamentDetails' => array(
'className' => 'TournamentDetails',
'foreignKey' => 'tournament_detail_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Controller data:
class TournamentsController extends AppController
function view($slug = null) {
if (!$slug) {
$this->Session->setFlash(__('Invalid Tournament.', true));
$this->redirect(array('action'=>'index'));
}
$this->Tournament->recursive = 1;
$tournament = $this->Tournament->findBySlug($slug);
$updates = $this->Tournament->TournamentDetail->Update->find('all', array('conditions' => array( 'tournament_details_id' => $this->data['TournamentDetails']['id'] )));
$this->set(compact('tournament','updates', $updates ));
Tournament view. This is display the 'tournament details' and (ideally) related tournament detail 'updates'
<h2><?php echo $tournament['Tournament']['name']; ?></h2>
<?php foreach ($tournament['TournamentDetail'] as $tournamentDetail): ?>
<h1><?php echo $tournamentDetail ['title']; ?></h1>
<p><?php echo $tournamentDetail ['body']; ?></p>
<?php endforeach; ?>
<?php foreach ($updates['Update'] as $update): ?>
<h4>Update: <?php echo $update ['date']; ?></h4>
<p> <?php echo $update ['Update'] ['title']; ?></p>
<p><?php echo $update ['Update'] ['body']; ?></p>
<?php endforeach; ?>
I've tested this by adding in the tournament details 'id' as an integer and it pulls up the correct 'update' record. However I seem to have problems configuring the find operation to do the same.
As always I appreciate the help.
Thanks
Paul
Based on your debug output, it seems that your $tournaments variable consists of an array (instead of the associative array) so you might want to use the foreach to access each of those elements:
foreach ($tournaments as $update):
?>
<h3>Updates</h3>
<h1><?php echo $update ['Update']['title']; ?></h1>
<p><?php echo $update ['Update']['body']; ?></p>
<hr/>
<?php endforeach; ?>
It appears that you be using the wrong variable, you talk about the $updates variable but you're using the $tournament variable in your view.
<?php foreach ($updates['Update'] as $update): ?>
<h3>Updates</h3>
<h1><?php echo $update ['title']; ?></h1>
<p><?php echo $update ['body']; ?></p>
<hr/>
<?php endforeach; ?>
Additionally you haven't posted the whole controller method, which includes that find but you might not have sent the data to the view yet either
$this->set(compact('updates'));

Resources