Showing posts with label Cakephp. Show all posts
Showing posts with label Cakephp. Show all posts

CakePHP query

CakePHP Find Query SUM() two fields from two different tables
You need to specify your SQL fragment in the fields array in the parameters of the find method.

$total = $this->Model->find('all', array(
  'fields' => array(
    'SUM(Model.price + OtherModel.price) AS total'
  ),
  'group' => 'Model.id'
));

Component

Controller function access from component

Controller Name: StagesController
Function Name: getStageByEntity
Parameter: CustomerQuotation

$this->controller->requestAction('Stages/getStageByEntity/CustomerQuotation')

function getStageByEntity($entity){       
    $this->loadModel($entity);
    $stage = $this->Stage->find('first',array('conditions'=>array('Stage.entity'=>$entity) ) );
    return $stage;
}
http://book.cakephp.org/2.0/en/controllers.html#Controller::requestAction

If you want to access any model from component
use
$this->controller
and add Model in $uses = array()
as
$this->controller->$ModelName->find('all');


CakePHP 3 belongsToMany example

http://stackoverflow.com/questions/26023045/using-belongstomany-association-in-cakephp-3

I have three tables categories, articles, articles_categories
 First is the articles table:

public function initialize(array $config)
    {
    parent::initialize($config);

    $this->belongsToMany('Categories',
        [
            'targetForeignKey' => 'category_id',
            'foreignKey' => 'article_id',
            'joinTable' => 'articles_categories',
        ]);

}

Next, the Categories table:

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->belongsToMany('Articles',
            [
                'targetForeignKey' => 'article_id',
                'foreignKey' => 'category_id',
                'joinTable' => 'articles_categories',
            ]);
    }

Now, the ContinuitiesController add() function:

$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
   
    $this->Articles->patchEntity($article, $this->request->data(), ['associated'=>['Categories']]);
    if ($result = $this->Articles->save($article, ['associated'=>['Categories']])) {
        $this->Flash->success(__('The article has been updated.'));
        return $this->redirect(['action' => 'index']);
    }

    $this->Flash->error(__('Unable to add your article.'));
}

$categoriesTable = TableRegistry::get('Categories');
$categories = $categoriesTable->find('list');
$this->set('categories', $categories);

$this->set('form_title', 'Add Article');
$this->set('article', $article);
$this->render('form');

 Now, the ContinuitiesController edit() function:

 $this->set('form_title', 'Edit Article');

$article = $this->Articles->find()->where(['id'=>$id])->contain('Categories')->first();

if ($this->request->is(['post', 'put'])) {
    $this->Articles->patchEntity($article, $this->request->data(), ['associated'=>['Categories']]);
    if ($result = $this->Articles->save($article, ['associated'=>['Categories']])) {
        $this->Flash->success(__('The article has been updated.'));
        return $this->redirect(['action' => 'index']);
    }
    $this->Flash->error(__('Unable to update the article.'));
}

$categoriesTable = TableRegistry::get('Categories');
$categories = $categoriesTable->find('list');
$this->set(compact('article', 'categories'));

$this->render('form');

And finally, the edit.ctp
echo $this->Form->input('categories._ids', ['options' => $categories, 'multiple'=>true]);

CakePHP Form

Controller:
Controller/PostsController.php
 <?php

class PostsController extends AppController {
    public $helpers = array('Html', 'Form');

    public function index(){
        $this->set('posts', $this->Post->find('all'));
    }

    public function view($id = null){
        if(!$id){
            throw new NotFoundException(__('Invalid post'));
        }
        $post = $this->Post->findById($id);

        if(!$post){
            throw new NotFoundException(__('Invalid post'));
        }
        $this->set('post', $post);
    }

    public function add(){
        $this->set('form_title', 'Add Post');

        $this->loadModel('category');
        $categories = $this->category->find('list');
        $this->set('categories', $categories);

        $this->edit();
    }
    public function edit($id = null){

        $this->set('form_title', 'Edit Post');


        $this->loadModel('category');
        $categories = $this->category->find('list');
        $this->set('categories', $categories);

        if($this->request->is('post') || $this->request->is('put') ){

            if($this->Post->save($this->request->data)){
                $this->redirect(array(
                    'controller' => 'posts',
                    'action' => 'index'
                ));
            }
        }

        if(!is_null($id)){
            $this->data  =   $this->Post->findById($id);
        }
        $this->render('form'); // Set the correct view
    }

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

        if ($this->Post->delete($id)) {
            //$this->Session->setFlash(__('The user with id: %s has been deleted.', h($id))
            $this->Session->setFlash("Record has been successfully deleted !", 'default', array('class' => 'alert alert-success'));

            return $this->redirect(array('action' => 'index'));
        }
    }

}

View:
View/Posts/form.ctp
 
<?php

echo '<h1>'.$form_title.'<h1>';
echo $this->Form->create('Post');
echo $this->Form->hidden('id');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows'=>'3'));

echo $this->Form->input('Post.Category',array('label'=>'Categories <span class="star">*</span>','class'=>'form-control multiple-select', 'multiple'=>true));

echo $this->Form->end('Save Post');
 
 

View/Posts/index.ctp







<h1>Blog posts</h1>
<?php echo $this->Html->link('Add post', array('action' => 'add')); ?>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Created</th>
        <th>Action</th>
    </tr>

    <?php if(!empty($posts)): ?>
        <?php foreach ($posts as $post): ?>
        <tr>
            <td><?php echo $post['Post']['id']; ?></td>
            <td>
                <?php echo $this->Html->link($post['Post']['title'], array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
            </td>
            <td><?php echo $post['Post']['created']; ?></td>
            <td>
                <?php
                echo $this->Html->link('Edit', array('action' => '/edit', $post['Post']['id'])).' ' ;
                echo $this->Form->postLink('Delete', array('action' => '/delete', $post['Post']['id']), array('confirm' => 'Are you sure you want to delete this Post?'));
                ?>
            </td>
        </tr>
        <?php endforeach; ?>
    <?php endif; ?>
    <?php unset($post); ?>
</table>

View/Posts/view.ctp

<h1><?php echo h($post['Post']['title']); ?></h1>

<p><small>Created: <?php echo $post['Post']['created']; ?></small></p>

<p><?php echo h($post['Post']['body']); ?></p>

Model/Post.php

<?php

App::uses('AppModel','Model', 'CakeSession');

class Post extends AppModel {

    public $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category',
            'joinTable' => 'category_posts',
            'foreignKey' => 'post_id',
            'associationForeignKey' => 'category_id',
            'unique' => 'keepExisting',
        )
    );

    public function beforeSave($options = array()) {

        foreach (array_keys($this->hasAndBelongsToMany) as $model){
            if(isset($this->data[$this->name][$model])){
                $this->data[$model][$model] = $this->data[$this->name][$model];
                unset($this->data[$this->name][$model]);
            }
        }

        return true;
    }
}