Different Views for connected Users in CakePHP - cakephp

I got 3 controller/tables Users / Adresses / AdressesUsers
This is my Adresses View function
/**
* View method
*
* #param string|null $id Adress id.
* #return \Cake\Network\Response|null
* #throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$this->viewBuilder()->layout('user');
$uid = $this->request->session()->read('Auth.User.id');
$adress = $this->Adresses->get($id, [
'contain' => ['Users']
]);
$counter = 0;
foreach($adress['users'] as $userid){
$users[$counter] = $userid['id'];
}
if(in_array($uid, $users)) {
$adress['dabei'] = 1;
} else {
$adress['dabei'] = 0;
}
$this->set('adress', $adress);
$this->set('_serialize', ['adress']);
}
I want all the users who are connected with the adress to see more detail information. How do I reach that goal? Tried to do it with a if clause, but didnĀ“t work, since I get an array of more then just one user (since multiple users can connect to one adress (adress of orders - not their own).
EDIT: I used an foreach loop to find out which users are in it and use an if/else in my view. But I think this is not best practice :/

Related

Laravel Orchid: How can the post entry in the database be retrieved from in the PostEditScreen.php?

Laravel Orchid: How can the post entry in the database be retrieved from in the PostEditScreen.php?
In a function in the PostEditScreen.php, how can the entry in the database that is being referred to by the PostEditScreen be accessed?
Post::find($post.id) is not working.
Any help would be greatly appreciated.
/**
* Query data.
*
* #param Post $post
*
* #return array
*/
public function query(Post $post): array
{
// This will already be a record of your model.
}
Or you can do it explicitly
/**
* Query data.
*
* #param int $id
*
* #return array
*/
public function query(int $id): array
{
Post::find($id)
}
This is stated in the laravel documentation: https://laravel.com/docs/7.x/routing#route-model-binding

How do I paginate a collection or custom query into API json in Laravel?

I have a complex query that is not based on any specific model table that I want to paginate output for. However laravel's built in pagination relies on models and tables. How can I paginate a collection and have the output match up with laravel's built in pagination output format?
I keep this in an app\Core\Helpers class so that I can call them from anywhere as \App\Core\Helpers::makePaginatorForCollection($query_results). The most likely place to use this is the last line of a controller that deals with complex queries.
In app/Http/Controllers/simpleExampleController.php
/**
* simpleExampleController
**/
public function myWeirdData(Request $request){
$my_unsafe_sql = '...';//never do this!!
$result = DB::statement(DB::raw($my_unsafe_sql));
return \App\Core\Helpers::makePaginatorForCollection($result);
}
In app\Core\Helpers.php or anywhere you like that auto loads.
/**
* This will match laravel's built in Model::paginate()
* because it uses the same underlying code.
*
* #param \Illuminate\Support\Collection $collection
*
* #return \Illuminate\Pagination\LengthAwarePaginator
*/
public static function makePaginatorForCollection(\Illuminate\Support\Collection $collection){
$current_page = (request()->has('page')? request()->page : 1) -1;//off by 1 (make zero start)
$per_page = (request()->has('per_page')? request()->per_page : config('api.pagination.per_page')) *1;//make numeric
$page_data = $collection->slice($current_page * $per_page, $per_page)->all();
return new \Illuminate\Pagination\LengthAwarePaginator(array_values($page_data), count($collection), $per_page);
}
/**
* Copy and refactor makePaginatorForCollection()
* if collection building is too slow.
*
* #param $array
*
* #return \Illuminate\Pagination\LengthAwarePaginator
*/
public static function makePaginatorForArray($array){
$collection = collect($array);
return self::makePaginatorForCollection($collection);
}

Drupal 7: Get all content items attached to all terms in a vocabulary sorted by date

Just like the title says. I have a vocabulary with several terms. I'd like to be able to get all items tagged by each of the terms in the vocabulary sorted by date created in one giant list. Is this possible with the built-in taxonomy API or am I going to have to build something custom?
As far as I know, there is no function/method in Drupal API will get that for you. I believe you will have to make your own.
When you say 'items' if you mean nodes then the function you are looking for is taxonomy_select_nodes().
https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_select_nodes/7
This function returns an array of node ids that match have the term selected.
/**
* Get an array of node id's that match terms in a given vocab.
*
* #param string $vocab_machine_name
* The vocabulary machine name.
*
* #return array
* An array of node ids.
*/
function _example_get_vocab_nids($vocab_machine_name) {
$vocabulary = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
if (!$vocabulary) {
return array();
}
$terms = taxonomy_get_tree($vocabulary->vid);
if (!$terms) {
return array();
}
$nids = array();
foreach ($terms as $term) {
$term_nids = taxonomy_select_nodes($term->tid, FALSE);
$nids = array_merge($nids, $term_nids);
}
return $nids;
}

Working with Virtual Fields when using model alias

I'm a CakePHP newbie. I have been looking for an answer to this for a while.
I followed directions from RichardAtHome in answer regarding autocomplete in CakePHP (autoComplete CakePHP 2.0).
I set up the function in my AppController.
This works very well with real fields but bugged when using Virtual Fields:
class Person extends AppModel {
public $virtualFields = array(
'name' => "CONCAT(Person.firstname, ' ', Person.lastname)"
);
}
I get this error: Column not found: 1054 Unknown column 'Person.name' in 'where clause'
When checking the SQL query I see this:
(CONCAT(`Person`.`firstname`, ' ', `Person`.`lastname`)) AS `Person__name`
This problem only occurs when I use $model = $this->{$this->modelClass}->alias;. Hardcording the model class in a specific controller (not AppController) works fine.
What do I need to do to make it work?
UPDATE:
After fiddling with this I discovered that it doesn't relate to $model = $this->{$this->modelClass}->alias; at all.
Instead I changed the 'conditions' value in the find() method and it all worked out fine. I am still puzzled as to why, but now it works just fine.
Incorrect code:
$result = $this->$model->find('all', array(
'conditions' => array(
$model . '.' . $field . " LIKE '%" . $term . "%'"
)
));
Correct code:
$result = $this->$model->find('all', array(
'conditions' => array(
$model . '.' . $field . " LIKE " => "%" . $term . "%"
)
));
That is an issue of the CakePHP core. You can't use a variable or another property within the declaration of a property. So you have to override the constructor and set your virtual fields there using $this->alias. The core has no automatic way to handle this internally so you have to take care of it.
The issue applies to all model properties by the way. We had the same issue with the $order property of the model. I'll paste the code here but you will have to modify the aliasPrefixing() method to not just go by the start of a string. Replace it by a regex and you should be fine to apply the prefix replacing method to all properties.
/**
* Constructor
*
* #param integer|string|array $id Set this ID for this model on startup, can also be an array of options, see above.
* #param string $table Name of database table to use.
* #param string $ds DataSource connection name.
*/
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->prefixOrderProperty();
}
/**
* Prefixes the order property with the actual alias if its a string or array
*
* The core fails on using the proper prefix when building the query with two
* different tables. Already reported this to the core team and might work on a
* core patch to fix this in the DboSource. The core fix should be done in DboSource,
* when reading the order property from the model.
*
* #return void
*/
public function prefixOrderProperty() {
if (is_string($this->order)) {
$this->order = $this->aliasPrefixing($this->order);
}
if (is_array($this->order)) {
foreach ($this->order as $key => $value) {
$this->order[$key] = $this->aliasPrefixing($value);
}
}
}
/**
* Checks if a string of a field name contains a dot if not it will add it and add the alias prefix
*
* #param string
* #return string
*/
public function aliasPrefixing($string) {
if (stripos($string, '.') === false) {
return $this->alias . '.' . $string;
}
return $string;
}

Get all permissions provided by given module via hook_permission()

How to list all permissions enabled by given module(s)?
I might be over simplifying the solution but to retrieve the permissions of a module you only need to execute the modules hook_permissions. e.g. call views_permission()
If your looking for all the permissions in the system then you can try calling user_permission_get_modules() which is part of the user module in core.
/**
* Determine the modules that permissions belong to.
*
* #return
* An associative array in the format $permission => $module.
*/
function user_permission_get_modules() {
$permissions = array();
foreach (module_implements('permission') as $module) {
$perms = module_invoke($module, 'permission');
foreach ($perms as $key => $value) {
$permissions[$key] = $module;
}
}
return $permissions;
}

Resources