What do I want to do
I want to list data that is pulled from the database with a certain condition.
What do I have and what does it do
I have a function that calls the data. When I print_r the data, it throws the correct stuff, so the query is executing directly. However, the display isn't working. It shows all the data in the database.
Here is my function:
public function myfunction() {
$adminExtensions = $this->AdminExtension->find('all',
array(
'conditions' => array('location_id'=>'3')
)
);
//print_r($adminExtensions);
$this->set('adminExtensions', $this->paginate());
}
What is the problem
The problem, as stated, is that it doesn't list just the records with location_id == 3. It lists everything.
I have narrowed it down to the last line of the function, but I can't seem to get the right code in there.
My display file (myfunction.ctp) is a basic baked cakePHP index file.
What am I doing wrong?
The code you currently have calls two different find operations. $this->AdminExtension->find() will return an array with all the AdminExtensions with a location_id of 3. The second $this->paginate() call just returns all possible results suitable for pagination in the view.
If you want to filter the paginated results you have to either configure the $paginate variable in the Controller or do it directly before you call $this->paginate.
class PostsController extends AppController {
public $paginate = array(
'conditions' => array('location_id'=>'3')
);
}
This will adjust pagination for all $this->paginate calls in the controller.
To do it for only one paginate call:
public function your_view() {
$this->set('adminExtensions', $this->paginate('AdminExtension', array('location_id' => '3')));
);
Related
I have a category model with the following method:
public static function index()
{
return self::has('posts')->paginate(1);
}
My category controller:
public function index()
{
$categories = Category::index();
return view('categories.index', compact('categories'));
}
This is what I've tried, I am using RefreshDatabase trait.
public function test_index_view_is_working()
{
factory(Post::class, 5)->create();
$response = $this->get(route('categories.index'));
$response->assertViewHas('categories', Category::index());
}
This test fails for some reason:
Failed asserting that two objects are equal.
at tests/Feature/CategoryTest.php:38
37| $response->assertViewIs('categories.index');
> 38| $response->assertViewHas('categories', Category::index());
--- Expected
+++ Actual
## ##
'dispatchesEvents' => Array ()
'observables' => Array ()
'relations' => Array (
+ 'posts' => Illuminate\Database\Eloquent\Collection Object (...)
)
'touches' => Array ()
'timestamps' => true
The reason you get this error is because somehow the posts are eager loaded from the view/controller but not from the tests.
I'm guessing return self::has('posts')->with('posts')->paginate(1); could fix it.
Alternatively, you can test if you have the pagination at the bottom the page. Since {{ $categories->links() }} will add something like Previous and Next you can still look for it.
$response = $this->get(route('categories.index'));
$response->assertSee('Next');
Also, you can ensure that you paginate the categories but it won't ensure you have added the links at the bottom of the page.
use Illuminate\Contracts\Pagination\Paginator;
...
$response = $this->get(route('categories.index'));
$this->assertInstanceOf(Paginator::class, $response->viewData('categories'));
Are you running any migrations/factories in the setUp method of the test?
It looks like maybe there are no post records in your database so $categories is coming into the view as null.
Also side note if all you want to do is make sure that the view has the variable $categories you can use $response->assertViewHas('categories');. This is not ideal if you are wanting to make sure your view is getting actual data.
I'm working on a site to make an inventory of series.
public function category(string $categoryName): Response
{
$categoryInfos = $this->getDoctrine()
->getRepository(Category::class)
->findOneByName($categoryName);
$programs = $this->getDoctrine()
->getRepository(Program::class)
->findByCategory($categoryInfos);
return $this->render('wild/category.html.twig', ['programs' => $programs, 'category' => $categoryInfos]);
}
This function allows me to retrieve all programs belonging to the specified category.
I would now like to limit the number of programs to 3 in my request.
$programs = $this->getDoctrine()
->getRepository(Program::class)
->findByCategory($categoryInfos)
->setMaxResults(3);
But this shows me the error:
-> Call to a member function setMaxResults() on array
What did I do wrong?
I get lost in the symfony doc, being new ^^
You are calling a method inside repository class that returns an array and you cannot execute setMaxResults() on arrays.
If you want to set the size of result you should set it inside findByCategory() method in ProgramRepository.php
I want to connect articles to pages but i get error last screen.
In your home page action
public function homepage() {
$this->loadModel('Articles');
$lastArticles = $this->Articles->find('all', ['limit' => 3, 'order' => 'Articles.created DESC'])->toArray();
$this->set('lastArticles', $lastArticles);
}
View::set expects 2 parameters, one being the name of the variable in the view and the 2nd being the values of that variable for the view.
You are in the PageController.php, I never used that controller for something else than the display() method. I don't know if what you're doing is the intended use.
If you want to list your articles I'd suggest you set that up in the ArticlesController.php.
//in src/Controller/ArticlesController.php
public function home() {
$lastArticles = $this->Articles->find('all', ['limit' => 3, 'order' => 'Articles.created DESC']);
$this->set('lastArticles', $lastArticles);
}
Then you need to create a view template named corresponding to the method name in the controller (see Naming Conventions) - for the method I posted it's "home.php".
//in templates/Articles/home.php
<?php foreach ($lastArticles as $lastArticle): ?>
//.. your fields ..
<?php endforeach; ?>
I am new to cakephp. I have a problem with calling the function. here is my issue.
In Contrloller file i get all the values using the following function
public function index()
{
$conditions = array(
'order' => array('Histroy.chat_sk DESC')
);
$this->set('histroys', $this->Histroy->find('all',$conditions));
}
In My model file have the following,
class Histroy extends AppModel
{
public $tablePrefix = 'plc_';
public $useTable = 'chat_history';
}
In my view file i have listed the values using foreach() function and that as follows
foreach ($histroys as $histroy):
$oper_name = $histroy['Histroy']['operator_fk'];
$operator_email = $histroy['Histroy']['email'];
endforeach
in that opertaor_fk is a field in history table. So i need get the operator name by another table as operators. So i need to call that function in the view.
Ex : In core we can do like as,
$operator_name = operator_name($fetch['operator_id']);
Function should be like this:
function operator_name($id)
{
// Select the value for the matched field in the operator
return $operator_name;
}
In cakephp how can i retrieve the values.
Please help me out to fix this. Thanks in Advance
Follow the blog tutorial for cake. It'll explain how to create associations and relationships between tables to let you do what is is you want, but in a nutshell, you need to create a relationship between History and Operator models and work from there.
I've a custom data provider in my Model
I tryied this in controller
public function actionMonthTotal()
{
$model=new Rapporti();
$this->render('monthTotal',array(
'dataProvider'=>$model->monthTotal(),
));
}
Where monthTotal is the model function that give me a DataProvider
Actually 'monthTotal' is a copy/past of view.php and it uses a clistView using _monthTotal, that is a copy/past of _view.php
I Need to simply get the dataset from dataProvider (a 'SELECT COUNT, SUM, SUM, etc...") and iterate into recordset to echo a simple TABLE into monthTotal view . So ...
how to use a dataProvider from a view to get records and how to iterate trough recors?
My month total is this and is in 'Report' Model
Actually report is in a relation Report N -> 1 Pionierato (sorry for italian terms, but are only object names)
public function totalMonth() {
$criteria = new CDbCriteria();
$criteria->with = array ('pionierato');
$criteria->condition = 'dataBetel=:month';
$criteria->select = "COUNT(t.id) as numProclamatori,
pionierato.tipo as tipoPionierato,
SUM(libri) as sommaLibri,
SUM(opuscoli) as sommaOpuscoli,
SUM(ore) as sommaOre,
SUM(riviste) as sommaRiviste,
SUM(visite) as sommaVisite,
SUM(studi) as sommaStudi";
$criteria->group = "t.dataBetel, t.pionieratoId";
$criteria->params = array ('month' => "2012-09-01");
$dataProvider=new CActiveDataProvider('Rapporti',
array ('criteria' => $criteria)
);
return $dataProvider;
}
I need to use this dataprovider to get the 3 record it will output and print a 3-row table. Static.
Using suggestion from first answer, i got this:
I obtained the result in this way:
<?php
foreach ($dataProvider->getData() as $id => $singleRecord) {
$this->renderPartial('_monthTotal', array('data' => $singleRecord));
}
?>
and removing the clistview widget.
But your answer helped my a lot, so I'll give my preference to you, thanks !
Try:
public function actionMonthTotal()
{
$model = Rapporti::model()->monthTotal();
$this->render('monthTotal',array(
'dataProvider'=>$model,
));
}
That should work, you are creating an object with the name $model which has a value equal to the return value of the method monthTotal() in the Rapporti model
If that doesn't work, check that you are actually getting a result from your monthTotal function by copying it (minus the return part) into your controller instead of calling it from the model.
In your monthTotal view you can iterate through the active records using CListView like so:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
Each iteration calls in a subview called "_view". The data for that record can be accessed using $data (eg: $data->id);
Here is an example of querying without using CActiveDataprovider:
$model = Rapporti::model()->findAll(array(
'condition' => 'dataBetel=:month',
...
));
You can try that... Alternatively you can use findAllBySql() instead of findAll() and type in your query that way. You will then be able to iterate through your data set using a foreach() loop