Using scripts_for_layout in plugin helper method - cakephp

i writing my menu plugin helper (similar to cakemenu)
and i want to you js and css related to my plugin
with in scripts_for_layout
how to add them to plugin helper method?
class AdminmenuHelper extends AppHelper {
var $helpers = array('Html', 'Javascript');
function show() {
$output = '
<ul>
<li><img src="/img/admin/icons/home.png" border="0" />;02=0O</li>
<li><img src="/img/admin/icons/document.png" border="0" />#>4C:F8O</li>
<li><img src="/img/admin/icons/document.png" border="0" />0B53>#88</li>
<li><img src="/img/admin/icons/door-open-in.png" border="0" />KE>4</li>
</ul>
';
return $output;
}

In your helper, you can add one of these 2 methods
#1
function beforeRender() {
$html = new HtmlHelper();
$html->script('custom', false);
}
#2
function beforeRender() {
$view =& ClassRegistry::getObject('view');
$view->addScript('<script type="tex/javscript" src="' . Router::url('/js/custom.js') . '"></script>');
}
#2 is lighter because it does not need to instantiate a new helper, but you have to write te entire javascript tag. It’s up to you to choose which one you like more.

Related

Want to Show images on blade template that stored in array formet in Database on Laravel 8

Please need help. I stored images as an array in the database. So how I decode the array images on the blade view template. My controller is like that
public function store(Request $req){
$req->validate([
'name' => 'required',
'imageFile' => 'required',
'imageFile.*' => 'mimes:jpeg,jpg,png,gif,csv,txt,pdf|max:2048'
]);
if($req->hasfile('imageFile')) {
foreach($req->file('imageFile') as $file)
{
$name = $file->getClientOriginalName();
$file->move(public_path().'/uploads/', $name);
$imgData[] = $name;
}
$fileModal = new Image();
$fileModal->name = $req->input('name');
$fileModal->image_path = json_encode($imgData);
$fileModal->save();
return back()->with('success', 'Images has successfully uploaded!');
}
}
and the image Model is like that...
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name',
'image_path'
];
}
I already successfully stored the data that images data as an array in the database.
But when I use this code it shows the array data, not images.
<img src="{{ URL::asset("uploads/".$photo->image_path) }}" alt="{{ $photo->name }}" style="width:150px; height:auto;">
After that, I will place another code :
#foreach ($photos as $photo)
#php $filenames = json_decode($photo->image_path); #endphp
#foreach ($filenames as $singlefilename)
<img src="{{ url('uploads/' . $singlefilename) }}" width="100px"/>
#endforeach
#endforeach
but at that time it shows all images that contained the folder but I need just that rows array images according to id. Please I need help. Anyone can help ?
You have bound multiple img paths with a single name, there is no key to pinpoint a single img path. It's like there is a group of people without identity, how can you find the one you want?

dynamically returning views by a foreach loop

I have a foreach loop that runs by my database:
<div id="nav" >
#foreach(\App\Categories::whereNull('parent_id')->get() as $category)
<a id="link1" href="{{ route('showCategory' , $category->id) }}" ><div class="link">{{ $category->name }}</div></a>
#endforeach
</div>
I want foreach link that adds by that it knows his path to the blades dynamically.
What should I do here?
My web.php:
Route::get('/category/{category}', 'PagesController#showCategory')->name('showCategory');
My controller:
public function showCategory(Categories $category) {
}
I'm guessing that you want to create a link for each category which goes to a page that displays more information about the selected category.
Your blade file in which you create the links for all the categories seems fine to me, but I'd recommend changing your route file to this:
Route::get('/category/{id}', 'PagesController#showCategory')->name('showCategory');
Then for your showCategory function, you would need something like this:
public function showCategory($id) {
$category = Categories::find($id);
// i used categories.show here, change it to whatever view you use
return view('categories.show')->with('category', $category);
}
Then in your categories.show view, you can access the properties of the category like so:
$category->id; // or whatever you want to display
As per OP's request: the first 5 categories in the database that lead to their pages:
In your controller:
public function myFunction()
{
$categories = Categories::all()->take(5)->get();
return view('your.view')->with('categories', $categories);
}
In your blade view (assuming that the view for the category is at: /category/id):
#foreach($categories as $category)
{{$category->name}}
#endforeach

CakePHP : Show database view

I have a view in my database and i want to show the value. but i confused how to call the name of view in my controller. i have made a model, but still i can't show the view. my view database’s name is Vtotaleks. Please help me T_T
here my controller
class HomesController extends AppController{
var $uses = array(
'Vtotaleks',
'SiswaMonitoring',
'Siswa',
'AuthUser',
'PerusahaanOrder');
public function index(){
$this->Lib->cekprivilege();
$totalEks = $this->Vtotaleks->find('all', array('cache' => true));
and this my model
<?php
class Vtotaleks extends AppModel
{
public $usetable = 'vtotaleks'; }
and this my view
<tbody>
<?php $totalEkstrainee=0;foreach($totalEks as $datatotalEks){
$totalEkstrainee+=$datatotalEks['Vtotalekstrainee']['siswa_total'];
?>
<tr>
<td><?php echo $datatotalEks['Vtotalekstrainee']['city_name']?></td>
<td align="right"><strong><?php echo $datatotalEks['Vtotalekstrainee']['siswa_total']?></strong></td>
</tr>
<?php }?>
<tr class="danger">
<td><em>Total</em></td>
<td align="right"><strong><?php echo $totalEkstrainee?></strong></td>
</tr>
</tbody>
and here the error
Notice (8): Undefined variable: totalEks [APP\View\Homes\index.ctp, line 142]
Warning (2): Invalid argument supplied for foreach() [APP\View\Homes\index.ctp, line 142]
Add this line after query
$this->set(compact('totalEks'));

Creating an arbitrary property in my Model

Here's my Model:
class Persona extends AppModel {
// This is just some arbitrary property I need to populate in the controller.
public $TipoPersona = '';
}
And here is the Action function in my Controller:
public function details($id = null) {
// Just a typical load by id.
$this->Persona->id = $id;
$this->set('persona', $this->Persona->read());
// Can I do something like?
$this->Persona->TipoPersona = "Mafa Woogly";
}
How can I set the $TipoPersona property in the "Model" here? My intent is to then use that property in the View like:
<tr>
<th>Tipo de Persona:</th>
<td><?php echo h($persona->TipoPersona); ?></td> // Or similar?
</tr>
Any suggestions?
This works, but feels wonky and not strongly typed.
public function details($id = null) {
$this->Persona->id = $id;
$this->set('persona', $this->Persona->read());
$this->set('tipoPersona', "Mafa woogly");
}
<tr>
<th>Tipo de Persona:</th>
<td><?php echo h($tipoPersona); ?></td>
</tr>
The method read() return an array, you can't get the property TipoPersona of this object.
I recommend you add a field in this table to specify type of person and than use the result of read(), like:
<?php echo $persona['Persona']['tipo_persona']; ?>
Try to add it directly with set:
$this->set('tipoPersona', $this->Persona->TipoPersona);
it's property like everyone else in the model. The same way you are setting $this->Persona->id few lines above :)
You could add it to the result array using Model::afterFind() callback.
Are you sure this shouldn't be a regular field in the Model?

How to overdrive FLASH MESSAGE default of cakePHP

For $this->Session->setFlash('this is message','flash_error'); you
only need to create flash_error.ctp in the elements folder to have a different look.
But what is with $this->Session->setFlash('this is message')? How do I modify the standard layout? I don't want to modify it with css or javascript.
Laheab answer is right. But you can override it using the AppController beforeRender function. In your app/app_controller.php write this function :
function beforeRender(){
if ($this->Session->check('Message.flash')) {
$flash = $this->Session->read('Message.flash');
if ($flash['element'] == 'default') {
$flash['element'] = 'flash_error';
$this->Session->write('Message.flash', $flash);
}
}
}
It will override the 'default' flash element with 'flash_error'. Then in app/views/elements create flash_error.ctp
The HTML for flash messages is output in the flash method of the SessionHelper class. I find the easiest way to achieve what you're trying to do is to override the core SessionHelper class. To do this
Copy lib/Cake/View/Helper/SessionHelper.php to app/View/Helper/SessionHelper.php
Cake will now use the SessionHelper class in your app as opposed to it's own. Now you can update the flash method to output the HTML you want. On line 136, you'll see this:
$out = '<div id="' . $key . 'Message" class="' . $class . '">' . $message . '</div>';
As an example, if I'm using Twitter Bootstrap, I'll update this line to be:
$out = '<div class="alert fade in"><a class="close" data-dismiss="alert" href="#">×</a>' . $message . '</div>';
According to CakePHP book entry on flash():
<?= $session->flash(); ?>
in a view file outputs:
<div id='flashMessage' class='message'>My Message</div>
So there is nothing to override but the CSS for this id in cake.generic.css.
Hope I understood the question correctly. =)
You cannot override default HTML for a flash message. What I did is: created the following function in app_controller:
protected function _f($message, $url=false) {
$this->Session->setFlash($message,'message');
if($url) $this->redirect($url);
}
Created my own message.ctp template in views/elements.
Then used the _f function inc all controllers like this:
$this->_f('This is a flash message','/page_to_redirect/');
Have you tried to create a default.ctp in elements folder?
That might be what you wanted?

Resources