So in my controller MenuController.php I have the following code:
class MenuController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this->set('menus', $this->Menu->find('all'));
$userSpecific = $this->Menu->find('all', array(
'conditions' => array('Menu.user_id' => '20')
));
}
}
and in my view, I am doing the following:
<?php foreach ($menus as $menu): ?>
<?php echo $menu['Menu']['id']; ?>
<?php echo $menu['Menu']['user_id']; ?>
<?php endforeach; ?>
update
To better understand this in my browser I changed my view to the following:
<?php foreach ($menus as $menu): ?>
<p>Menu id <?php echo $menu['Menu']['id']; ?> is for user: <?php echo $menu['Menu']['user_id']; ?></p>
<?php endforeach; ?>
end update
Now in the view, it is currently using the $this and returning all values from the database table, How do I change the view to use $userSpecific rather than $this I managed to get this far (making the $userSpecific part) by using the cookbook but I could only find the controller side and not the view side. I'm sorry if it's a bad question, just trying to learn.
You need to send the data to the view from the controller at the end of the index() function.
You can do it like this:
$this->set('userSpecific', $userSpecific);
or like this (my preferred way)
$this->set(compact('userSpecific');
Once you've done this, you can then modify your view to show the user specific fields as shown:
<?php foreach ($userSpecific as $menu): ?>
<?php echo $menu['Menu']['id']; ?>
<?php echo $menu['Menu']['user_id']; ?>
<?php endforeach; ?>
Related
I am starting to learn Yii framework so I am a beginner. I am struggling. I want to fetch the data from database using yii2 framework. This is my controller
public function actionView()
{
$this->view->title = 'List Hotels';
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
return $this->render('index', [
'items' => $items,
]);
}
In my view file, I used the fetched data as below;
<?php
/* #var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Hotel list';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php foreach ($items as $item): ?>
<p> <?= $item-> name ?></p>
<p> <?= $item->address ?></p>
<p> <?= $item->description ?></p>
<?php endforeach; ?>
When I wrote var_dumps($items) under $items I can see the datas. However in the view It says Trying to get property 'name' of non-object. What did I wrong here please guide me. THanks for your time.
ArrayHelper::map()
Returns an array where, in your case, second argument passed is a key, the third is a value. So you need to access its elements as an array elements instead of class properties. Like:
<?php foreach ($items as $key => $value): ?>
<p> <?= $key ?></p>
<p> <?= $value ?></p>
<?php endforeach; ?>
More details here: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
But if you need to access data as class properties change the line in your controller:
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
to:
$items = Hotel::find()->all();
$items = Hotel::find()->all();
I should not add Array Helper
I created a method in a model of CI4 to query a search results. I need to paginate search results but the URL not provide results. I need to standard way for pagination in CI4.
Here is model method -
<?php
public function search($key)
{
$builder = $this->table('apps_common_all');
$builder->Like('name',$key,'after');
$query = $builder->paginate(51);
return $query;
}
?>
controller method is -
<?php
public function result()
{
$key = $this->request->getVar('s');
$apps = new AppsModel();
$data = [
'items' => $apps->search($key),
'pager' => $apps->pager,
];
return view('search/index',$data);
}
?>
Pagination code in view page
<?php if ($pager) :?>
<?php $pagi_path=getenv('pagi_path').'search_result'; ?>
<?php $pager->setPath($pagi_path); ?>
<?= $pager->links() ?>
<?php endif ?>
when pagination link clicked the url not provide results
http://myshahadat.com/demo/apkdownload/search_result?s=a&page=2
and my route is
<?php $routes->get('/search_result', 'Search::result'); ?>
i try to solve this problem and read many post but nothing help me, try to figure out my problem, as i am new to laravel!
this is my Index.blade.view located in view/posts
<!DOCTYPE html>
<html>
<head>
<title>Post</title>
</head>
<body>
<ul>
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
}
?>
</ul>
</body>
</html>
PostController :
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index(){
$posts = Post::all();
return view('posts.index',compact($posts));
}
public function showPost($id){
$post = Post::find($id);
return view('posts.post',compact($post));
}
}
i read many post related to this but nothing help me, what i am doing wrong?
this is the problem i am facing : Undefined variable: posts (View: C:\xampp\htdocs\firstApplication\resources\views\posts\index.blade.php)
Let's assume you have another variable holding data, then your index method should look like:
Access content of $post as $post->id instead of $post->$id
public function index(){
$posts = Post::all();
$someData = []; // extra variable
return view('posts.index',compact('posts','someData'));
}
Another Change to be made is in view file:
On a side note: you don't have to use traditional PHP tags and foreach, instead you could use Laravel's clean and elegant method like following:
Replace your block of code:
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
}
?>
Updated code:
#foreach($posts as $post)
<li><a href = "{{ url('post/'. $post->id) }}" </a></li>
#endforeach
Change view to
</head>
<body>
<ul>
<?php
foreach ($posts as $post) {
echo "<li><a href = 'post/$post->id'>".$post->title."</a></li>";
}
?>
</ul>
</body>
</html>
Change $post->$id to $post->id and $post->$title to $post->title
Also compact($posts) to compact('posts') and compact($post) to compact('post')
I am trying to add links to a Tree output list.
In addition to the links I get the  's included in the output
So that it looks like this:
**My Categories
Fun
Sport
Surfing
Extreme knitting**
etc.....
I don't want that obviously, but I do want to keep the nested output relationship.
Below is code:
Controller
<?php
class CategoriesController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this->set('output', $this->Category->generateTreeList(null, null, null, ' '));
}
}
?>
View
<?php foreach ($output as $data): ?>
<ul>
<?php echo $this->Html->link($data,
array('controller' => 'data', 'action' => 'view', $data)); ?>
</ul>
<?php endforeach; ?>
<?php unset($data); ?>
You should use a tree helper to output your tree as ul/li including links.
See http://www.dereuromark.de/2013/02/17/cakephp-and-tree-structures/
generateTreeList() - as documented - is a quick way to create a dropdown select ready list, not a tree.
I'm facing validation problems integrating my custom module in zfcAdmin and BjyAuthorize.
My form class:
...
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $field){
if (isset($field['field']))
$this->add($field['field']);
}
...
My filter class:
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $filter){
if (isset($filter['filter']))
$this->add($filter['filter']);
}
...
Fields, filters and other options are retrieved from config file.
Basically everything works fine: form data can be added, edited or deleted from db.
Also after the zfcAdmin module installation no problem rose. Everything works fine using both 'site/mymodule' route and 'site/admin/mymodule' route: i can still add, edit and delete items from db.
Here the problem: I need some form elements (a Select in this particular case) editable/viewable only by administrator. (I can write a new controller/entity class 'ad hoc' for admin but i would like to use the same code for the whole site.)
I installed and configured bjyoungblood/BjyAuthorize module: it allowed me to display some form elements/fields only to admin but when i'm in edit mode a form validation error is displayed: "Value is required and can't be empty"
Here the code:
//view/mymodule/mymodule/update.phtml
<div id="page" style="margin-top: 50px;">
<?php if (isset($this->messages) && count($this->messages) > 0 ): ?>
<?php foreach ($this->messages as $msg): ?>
<div class="alert alert-<?php echo $this->escapeHtmlAttr($msg['type']); ?>">
<?php if (isset($msg['icon'])) echo '<i class="'.$this->escapeHtmlAttr($msg['icon']).'"></i> '; ?><?php echo $this->escapeHtml($msg['message']); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php
$title = 'Edit Item';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url($this->route . 'mymodule/update', array('action' => 'update', 'id' => $this->id )));
$form->prepare();
$form->setAttribute('method', 'post');
$input = $form->getInputFilter();
?>
<?php echo $this->form()->openTag($form) ?>
<dl class="zend_form">
<?php foreach ($form as $element): ?>
<?php
//CHECK USER PRIVILEDGES
$elName = $element->getName();
$elResource = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['resource'] : "userresource";
$elPrivilege = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['privilege'] : "view";
//SHOW THE ELEMENT IF ALLOWED
if($this->isAllowed($elResource, $elPrivilege)):
?>
<?php if ($element->getLabel() != null): ?>
<dt><?php echo $this->formLabel($element) ?></dt>
<?php endif ?>
<?php if ($element instanceof Zend\Form\Element\Button): ?>
<dd><?php echo $this->formButton($element) ?></dd>
<?php elseif ($element instanceof Zend\Form\Element\Select): ?>
<dd><?php echo $this->formSelect($element) . $this->formElementErrors($element) ?></dd>
<?php else: ?>
<dd><?php echo $this->formInput($element) . $this->formElementErrors($element) ?></dd>
<?php endif ?>
<?php else: ?>
<?php
?>
<?php endif ?>
<?php endforeach ?>
</dl>
<?php echo $this->form()->closeTag() ?>
</div>
<div class="clear-both"></div>
My controller action
//controller
public function updateAction(){
$messages = array();
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
$form = $this->getServiceLocator()->get('FormItemService');
$itemMapper = $this->getItemMapper();
$item = $itemMapper->findById($id);
$form->bind($item);
$request = $this->getRequest();
if($request->isPost()){
$form->setData($request->getPost());
if ($form->isValid()) {
die('c');//never here
$service = $this->getServiceLocator()->get('mymodule\Service\Item');
if ( $service->save($form->getData()) )
{
$messages[] = array(
'type' => 'success',
'icon' => 'icon-ok-sign',
'message' => 'Your profile has been updated successfully!',
);
}
else
{
$messages[] = array(
'type' => 'error',
'icon' => 'icon-remove-sign',
'message' => 'Profile update failed! See error messages below for more details.',
);
}
}else{
var_dump($form->getMessages());//Value is required and can't be empty
}
}
return array(
'messages' => $messages,
'form' => $form,
'id' => $id,
'form_options' => $this->getServiceLocator()->get('mymodule_module_options')->getFormSettings(),
'route' => $this->checkRoute($this->getEvent()->getRouteMatch()->getmatchedRouteName())
);
}
If user is not allowed to view the resource, the element is not echoed. So $request->getPost() has no value for that form element and an error is returned by isValid().
Has anyone solved a similar problem or can anyone point me to the right direction?
Thanks
The problem is that you don't do any security check in your FormFilter class, where you define your required fields.
The $form->isValid() function checks the posted data against those filter elements. So it's not enough to prevent the 'echo field' in your view, you still need to apply the security check to the filter element.
One other approach would be to make two forms one for the front end and one for the admin. Since the one for the admin will have the same fields plus one extra select field you can make the admin form extends the front end one. E.g.
class myForm
{
public function __construct(...)
{
// add fields and set validators
}
}
and the admin form could be:
class MyAdminForm extends myForm
{
public function __construct(...)
{
parent::__construct(...);
// add the extra field and extra validator
}
}
In that way even if you edit the front end form (or validators) the back end will always be up to date.
Hope this helps :),
Stoyan