PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cakephp-3.1. Show all posts
Showing posts with label cakephp-3.1. Show all posts

Sunday, March 13, 2022

[FIXED] How to Filter Associated Data using FriendsOfCake Search plugin for CakePHP 3.1.0

 March 13, 2022     cakephp, cakephp-3.1, php     No comments   

Issue

Plugin: FriendsOfCake\Search

CakePHP: 3.1.0

I'm currently adding the ability to filter my Orders controller on the index() method. I'm needing to be able to search Orders my the name of the User who placed the order. Each order is associated with the Users model:

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

When I build my searchConfiguration() method in the OrdersTable.php file I have the following:

    ->value('first_name', [
        'field' => $this->aliasField('Users.first_name')
    ])
    ->value('last_name', [
        'field' => $this->aliasField('Users.last_name')
    ])

The Orders index() method

    $query = $this->Orders->find('search', 
        $this->Orders->filterParams($this->request->query))->contain(['Users', 'PaymentMethods', 'Industries']
    )->order(['Orders.created' => 'DESC']);
    $this->set('orders', $this->paginate($query));

This loads fine when I'm not passing any parameters to the query, however, as soon as I try and search by first_name or last_name I get the error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Orders.Users.first_name' in 'where clause'

Based on the error, it's appending Orders. to the field that I'm trying to search by. From what I can tell CakePHP has 2 methods aliasField() one in \var\www\<project_name>\vendors\cakephp\cakephp\src\ORM\Query.php

public function aliasField($field, $alias = null)
{
    $namespaced = strpos($field, '.') !== false;
    $aliasedField = $field;

    if ($namespaced) {
        list($alias, $field) = explode('.', $field);
    }

    if (!$alias) {
        $alias = $this->repository()->alias();
    }

    $key = sprintf('%s__%s', $alias, $field);
    if (!$namespaced) {
        $aliasedField = $alias . '.' . $field;
    }

    return [$key => $aliasedField];
}

And one in \var\www\<project_name>\vendors\cakephp\cakephp\src\ORM\Table.php

public function aliasField($field)
{
    return $this->alias() . '.' . $field;
}

It appears that Query.php will allow you to specify the $alias for the field, however, Table.php does not, so I assume that's the method that's being used here.

Can anyone give me guidance on how to filter on data contained in an associated table?


Solution

Simply either do not use aliasField() when you're already supplying the alias

'field' => 'Users.first_name'

or use aliasField() on the associated Users table

'field' => $this->Users->target()->aliasField('first_name')

Using Query::aliasField() would be totally wrong, as this will return a key => value array for use with Query::select().



Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 22, 2022

[FIXED] How to delete data in custom finder method in CakePHP 3

 February 22, 2022     cakephp-3.0, cakephp-3.1, cakephp-3.x     No comments   

Issue

I want to delete data in custom finder method.

Custom finder method document

My code:

public function findPREACTIVE(Query $query, array $options) {
    $query->delete()
            ->where(['member_status' => -1])
            ->andWhere(['registered >= DATE_SUB(NOW(), INTERVAL 72 HOUR)'])->execute();

    return $query
                    ->where(['email' => $options['email'], 'token_key' => $options['token_key']])
                    ->andWhere(['member_status' => -1])
                    ->andWhere(['registered < DATE_SUB(NOW(), INTERVAL 72 HOUR)']);
}

When i call this finder, i get error:

You cannot call all() on a non-select query. Use execute() instead.

Is there have solution for this case?


Solution

You'll have to issue a separate query. What you are doing there will mess up the finder query, which is ment to be a select query.

$this
    ->query()
    ->delete()
    ->where(['member_status' => -1])
    ->andWhere(['registered >= DATE_SUB(NOW(), INTERVAL 72 HOUR)'])->execute();

Use applyOptions() in case you need the finder options to be applied to the delete query too.

$this
    ->query()
    ->delete()
    ->applyOptions($options)
    // ...


Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I generate a pdf using CakePhp v3.x

 February 22, 2022     cakephp, cakephp-3.0, cakephp-3.1, pdf, pdf-generation     No comments   

Issue

I'm using CakePHP v3.x, how can I generate a PDF file?

There is the possibility to generate an "only for download" or "only for print" file? (which doesn't need to be saved on server)


Solution

How can I generate a pdf using CakePhp v3.x?
Here's a plugin for this: https://github.com/FriendsOfCake/CakePdf



Answered By - user3082321
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where to set CakePHP 3 cookie config

 February 22, 2022     cakephp-3.0, cakephp-3.1     No comments   

Issue

I want to set the config for the cookie component but I am unsure where to add the code.

Do I set it in the AppController or the bootstrap?

public function initialize()
{
    parent::initialize();

    $this->loadComponent('Csrf');

    $this->Cookie->config([
        'httpOnly' => true
    ]);

}

Solution

According to http://book.cakephp.org/3.0/en/controllers/components.html#configuring-components

Some examples of components requiring configuration are Authentication and Cookie. Configuration for these components, and for components in general, is usually done via loadComponent() in your Controller’s initialize() method or via the $components array.

Assuming that you need to configure it globally, you should place the configurationcode into the initialize() of the AppController.

If you want to override the configuration at runtime, you can place the code into the beforeFilter() of a controller.



Answered By - Sevvlor
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 21, 2022

[FIXED] cakephp 3.1 input field with european date format

 February 21, 2022     cakephp, cakephp-3.0, cakephp-3.1, date     No comments   

Issue

I have a table with records of users (name, forename, birthdate, etc.) and I want to find users by name or birthdate or every possible combination of this.

My code works well, but the birthdate is stored in the american format (YYYY-MM-dd), so I have to search after dates in this format to get the right record. That´s really annoying, because in Germany we use the european format (dd.MM.YYYY) and I want to search for the dates by our habitual format. Now I need help to give the input field the european format and get the right record.

I hope, you understand my issue. :)

Here is an extract of my Controller-Code:

$name = $this->request->data['name'];
$forename = $this->request->data['forename'];
$birthdate = $this->request->data['birthdate'];

if($name || $forename || $birthdate){

    $query = $this->find()
                  ->where([
                     'name LIKE' => '%'.$name.'%',
                     'forename LIKE' => '%'.$forename.'%',
                     'birthdate LIKE' => '%'.$birthdate.'%'
                  ]);

    $number = $query->count();
    $this->set('users', $this->paginate($query));
    $this->set('_serialize', ['users']);

}

And here is the related part of the code from my view:

foreach($users as $user):
    h($user->name)
    h($user->forename)
    h($user->birthdate)
endforeach;

Thank you very much.


Solution

Your birthdate is stored correctly.

set in bootstrap.php

/**
 * Set the default locale. This controls how dates, number and currency is
 * formatted and sets the default language to use for translations.
 */    
ini_set('intl.default_locale', 'de_DE');

http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#setting-the-default-locale

view / search form

<?= $this->From->input('birthdate',['type' => 'text']); ?>

use js / jquery date picker

$('#datepicker').datepicker({ dateFormat: 'dd.mm.yy' }); 


Answered By - Salines
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] CakePHP 3 & Mercury: SMTP server did not accept the password

 February 21, 2022     cakephp, cakephp-3.0, cakephp-3.1, email, xampp     No comments   

Issue

I have localhost xampp server with Mercury mail server. With Thunderbird email client I can send and recive mails from localhost.

But when try send with CakePHP 3.1.x i got error message:

SMTP server did not accept the password.

i use same login data:

    'EmailTransport' => [
    'default' => [
        'className' => 'Smtp',
        // The following keys are used in SMTP transports
        'host' => 'localhost.dev',
        'port' => 25,
        'timeout' => 30,
        'username' => 'info',
        'password' => 'info',
        'client' => null,
        'tls' => null,
    ],
],

Mercury log when send and recive with Thunderbird

T 20151202 221930 565f69f1 Connection from 127.0.0.1
T 20151202 221930 565f69f1 EHLO [127.0.0.1]
T 20151202 221930 565f69f1 MAIL FROM:<nikola@localhost.dev> SIZE=385
T 20151202 221930 565f69f1 RCPT TO:<info@localhost.dev>
T 20151202 221930 565f69f1 DATA
T 20151202 221930 565f69f1 DATA - 12 lines, 385 bytes.
T 20151202 221930 565f69f1 QUIT
T 20151202 221930 565f69f1 Connection closed with 127.0.0.1, 0 sec. elapsed.

Mercury log when try to send and recive with CAKEPHP

T 20151202 222318 565f69f2 Connection from 127.0.0.1
T 20151202 222318 565f69f2 EHLO localhost
T 20151202 222318 565f69f2 AUTH LOGIN
T 20151202 222318 565f69f2 QUIT
T 20151202 222318 565f69f2 Connection closed with 127.0.0.1, 0 sec. elapsed.

Solution

If anyone ever had the same problem, the solution is:

 'password' => null,


Answered By - Salines
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 16, 2022

[FIXED] Cakephp 3.1 - How to redirect based on query string values?

 February 16, 2022     cakephp, cakephp-3.1, redirect, url-routing     No comments   

Issue

We recently updated our site from pure php to cakephp 3 and having trouble redirecting urls that have params to a new url.

For example this redirect works fine

$routes->redirect('/webcast.php', '/webcast', ['status' => 302]);

But if there's parameters, it doesn't work

$routes->redirect('/webcast.php?id=100', '/webcast', ['status' => 302]);

Any ideas?

Thanks.


Solution

The router doesn't support matching on query strings, the URL passed to the router when checking for a matching route won't have any query string values attached anymore.

While it would be possible to workaround this by using a custom routing dispatcher filter, a custom/extended Router class, and a custom/extended RouteCollection class, this seems like way too much work for something that can easily be defined as for example a rewrite rule on server level.

Apache mod_rewrite example:

RewriteCond %{QUERY_STRING} ^id=100$
RewriteRule ^webcast\.php$ /webcast? [L,R=302]

And note that 301 is usually the preferred redirect method.

See also

  • Apache > HTTP Server > Documentation > Version 2.4 > Apache mod_rewrite


Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 17, 2022

[FIXED] Is it possible to use AppController on error pages? (Cakephp 3.1)

 January 17, 2022     cakephp, cakephp-3.0, cakephp-3.1     No comments   

Issue

I am trying to render error templates (eg error400.ctp) but with the default layout (site header and footer) which relies on components and variables set in AppController. How do I tell Cake to use AppController when rendering error pages?

I have already tried making an ErrorController which extends AppController, but it breaks for missing actions.


Solution

Here's my working ErrorController in case anyone comes looking for it:

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Event\Event;

class ErrorController extends AppController
{

    public function beforeRender(Event $event)
    {
        parent::beforeRender($event);
        $this->viewBuilder()->templatePath('Error');
    }

}

There was a bug in one of my Components being loaded in AppController. When ErrorController extends AppController and one tries to access an invalid action in a controller it creates two instances of AppController and in my case a duplicate declaration of class error was thrown because of a bug in my component. This error caused some kind of loop causing the error page not to render.



Answered By - Test Testington
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing