0

Hi all Iam using Cakephp 2.x, I need to output individual users' comments for each individual event. Each user has many events and many comments. I have Events, Comments and Users models and want to allow users to post and view comments on each event view.ctp. If anyone could give any starting tips to implement this functionality it would be much appreciated.

I have tried to output the comments model index table in the events view.ctp, but the table is not populated with the comments from the database, but the comments view.ctp does in fact populate the table with the comments. I have used the $this->loadModel('Comments'); function in the events controller.

<div class="events view">
    <?php echo $this->Html->css('viewevent'); ?>
    <?php echo $this->element('maintitlegen'); ?>

    <div style="padding-top: 160px">
    <h2><?php  echo $event['Event']['name']; ?></h2>
    <dl>

        <dt><?php echo __('Event Image'); ?></dt>
        <dd>
            <?php echo $this->Html->image('/uploads/event/filename/thumb/small/'.$event['Event']['filename']); ?>
            &nbsp;
        </dd>


        <dt><?php echo __('Date'); ?></dt>
        <dd>
            <?php echo h($event['Event']['date']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Time'); ?></dt>
        <dd>
            <?php echo h($event['Event']['time']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Description'); ?></dt>
        <dd>
            <?php echo h($event['Event']['description']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Dresscode'); ?></dt>
        <dd>
            <?php echo h($event['Event']['dresscode']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Slogan'); ?></dt>
        <dd>
            <?php echo h($event['Event']['slogan']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Price'); ?></dt>
        <dd>
            <?php echo h($event['Event']['price']); ?>
            &nbsp;
        </dd>
        <dt><?php echo __('Offers'); ?></dt>
        <dd>
            <?php echo h($event['Event']['offers']); ?>
            &nbsp;
        </dd>


    </dl>

    <!--<?php foreach ($users as $user): ?>
    <?php echo $user['Comment']['comment']; ?>
    <?php endforeach; ?>-->
    <!--<?php echo $ucomment['Comment']['comment']; ?>-->



    <?php echo $this->Form->create('Comment', array('controller' => 'comments', 'action' => 'add')); ?>
    <?php echo ('Add Comment'); ?>
    <?php echo $this->Form->input('comment'); ?>
    <?php echo $this->Form->end('Submit'); ?>

</div>
<div class="comments index">
    <h2><?php echo ('Comments'); ?></h2>
    <table cellpadding="0" cellspacing="0">
    <tr>
            <th><?php echo $this->Paginator->sort('id'); ?></th>
            <th><?php echo $this->Paginator->sort('comment'); ?></th>
            <th><?php echo $this->Paginator->sort('created'); ?></th>
            <th><?php echo $this->Paginator->sort('modified'); ?></th>
            <th><?php echo $this->Paginator->sort('user_id'); ?></th>
            <th><?php echo $this->Paginator->sort('event_id'); ?></th>
            <th class="actions"><?php echo __('Actions'); ?></th>
    </tr>
    <?php
    foreach ($comments as $comment): ?>
    <tr>
        <td><?php echo h($comment['Comment']['id']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['comment']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['created']); ?>&nbsp;</td>
        <td><?php echo h($comment['Comment']['modified']); ?>&nbsp;</td>
        <td>
            <?php echo $this->Html->link($comment['User']['name'], array('controller' => 'users', 'action' => 'view', $comment['User']['id'])); ?>
        </td>
        <td>
            <?php echo $this->Html->link($comment['Event']['name'], array('controller' => 'events', 'action' => 'view', $comment['Event']['id'])); ?>
        </td>
        <td class="actions">
            <?php echo $this->Html->link(__('View'), array('action' => 'view', $comment['Comment']['id'])); ?>
            <?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $comment['Comment']['id'])); ?>
            <?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $comment['Comment']['id']), null, __('Are you sure you want to delete # %s?', $comment['Comment']['id'])); ?>
        </td>
    </tr>
<?php endforeach; ?>
    </table>
    <p>
    <?php
    echo $this->Paginator->counter(array(
    'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
    ));
    ?>  </p>

    <div class="paging">
    <?php
        echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
        echo $this->Paginator->numbers(array('separator' => ''));
        echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
    ?>
    </div>
</div>
</div>

////////////////////////////////User model///////////////////////////////////////////////

<?php
class User extends AppModel {
    public $name = 'User';
    public $displayField = 'name';

    public $validate = array(
        'name'=>array(
            'Please enter your name.'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please enter your name.'
            )
        ),
        'username'=>array(

            'That username has already been taken'=>array(
                'rule'=>'isUnique',
                'message'=>'That username has already been taken.'
            ),
            'Valid email'=>array(
                'rule'=>array('email'),
                'message'=>'Please enter a valid email address'
            )
        ),
        'email'=>array(
            'Valid email'=>array(
                'rule'=>array('email'),
                'message'=>'Please enter a valid email address'
            )
        ),
        'password'=>array(
            'Not empty'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please enter your password'
            ),
            'Match passwords'=>array(
                'rule'=>'matchPasswords',
                'message'=>'Your passwords do not match'
            )
        ),
        'password_confirmation'=>array(
            'Not empty'=>array(
                'rule'=>'notEmpty',
                'message'=>'Please confirm your password'
            )
        )
    );

    public function matchPasswords($data) {
        if ($data['password'] == $this->data['User']['password_confirmation']) {
            return true;
        }
        $this->invalidate('password_confirmation', 'Your passwords do not match');
        return false;
    }

    public function beforeSave($options = array()) {
        if (isset($this->data['User']['password'])) {
            $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        }
        return true;
    }

    public $hasMany = array(
        'Event' => array(
            'className' => 'Event',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),

        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )

        );

        public $hasOne = array(
            'Profile' => array(
            'className' => 'Profile',
            'foreignKey' => 'user_id',
            'dependent' => true));

        var $actsAs = array(
        'MeioUpload.MeioUpload' => array('filename'=>array(
         'thumbsizes'=>array(
         'small'=>array(
         'width'=>'75',
         'height'=>'75',
         'forceAspectRatio'=>'C'
                        )))));


}
?>

///////////////////////////////////// Users Controller///////////////////////////////////

<?php
class UsersController extends AppController {

    public $name = 'Users';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }

    public function isAuthorized($user) {
        if ($user['role'] == 'admin') {
            return true;
        }
        // if (in_array($this->action, array('delete'))) {
            // if ($user['id'] != $this->request->params['pass'][0]) {
                // return false;
            // }
        // }

        return true;
    }

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());   
            } else {
                $this->Session->setFlash('Your username/password combination was incorrect');
            }
        }
    }

    // public function logout() {
        // $this->redirect($this->Auth->logout());
    // }


    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->User->find('all'));
    }

    public function view($id = null) {
        $this->User->id = $id;

        if (!$this->User->exists()) {
            throw new NotFoundException('Invalid user');
        }

        if (!$id) {
            $this->Session->setFlash('Invalid user');
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read());
    }

    public function add() {
        if ($this->request->is('post')) {

            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('Now create your profile!');
                $this->Auth->login();
                $this->redirect(array('controller'=> 'profiles', 'action' => 'add'));
            } else {
                $this->Session->setFlash('Your account cannot be created. Please try again.');
            }
        }
        // if (!empty($user)){
                // $this->request->data['Profile']['user_id'] = $this->User->id;
                // $this->User->Profile->save($this->request->data);
            // }

    }

    public function edit($id = null) {
    $this->User->id = $id;
    $user = $this->User->read();

    if($user['User']['id'] != $this->Auth->user('id')){
        $this->redirect(array('controller' => 'events','action' => 'index'));
    }

    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }

    if ($this->request->is('get')) {
        $this->request->data = $user;
    } else {
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('Your account has been updated'));
            $this->redirect(array('controller' => 'events', 'action' => 'index'));
        } else {
           $this->Session->setFlash(__('Your account cannot be saved. Please try again.'));
        }
    }
}

    public function delete($id = null) {
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        if (!$id) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash('User deleted');
            $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash('User was not deleted');
        $this->redirect(array('action' => 'index'));
    }
}
?>
Joshua
  • 371
  • 2
  • 6
  • 23
  • Would be handy to see your model for your user, but to check, just print_r($event) see if it contains a users array inside of it, if it does, great you're almost there, if it doesn't then your models are setup wrong. Also what happens if you print_r($event['User']); – Mark Jan 05 '13 at 17:14
  • Post your model and controller, it would make it a lot easier to help. I don't think the view would be the problem here. – Eoin Murphy Jan 05 '13 at 17:16
  • I have posted my user model here – Joshua Jan 05 '13 at 17:23
  • The is my output for print_r($event['User']); - Array ( [id] => 19 [name] => Daniel Toppin [username] => Daniel [email] => daniel@gmail.com [password] => 8ecf7bb874637ae1617570e95caf10ed183bbef3 [role] => [filename] => [dir] => [mimetype] => [filesize] => [created] => 2012-12-10 22:20:26 [modified] => 2012-12-10 22:20:26 ) – Joshua Jan 05 '13 at 17:45
  • It will be your Events model and controller that we'll need to see in order to help, so post that. And if you were to just use the Cake Bake console to build your models, controllers and views, then Cake would automatically display the Comments for each Event in the Event view.ctp file. Thats assuming your database structure is correct (ie, Comments has a user_id and an event_id field, and Events has a user_id field). Did you start by building your app using the Cake Bake console? – joshua.paling Jan 05 '13 at 23:40

1 Answers1

0

I think it is safe to assume your comment table has at least the following columns:

  • id
  • user_id
  • event_id
  • comment (or name)

The view you display in the OP is the view for the events.view method. But you do not show the even model or controller. So I am not certain if you need help with the events controller or if you are trying to display event data in the users controller. The way to get all of the comments for the view you show in the OP is to pull all of the comments from the model like so:

$this->set('comments', $this->Event->Comment->find('all', array('conditions' => array('event_id' => $event_id))));

If you want the user data to be displayed along with it, you will need to either set recursive = 1 or write a join to join the user data.

Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74