Use of different Method from Controller on Button in HTML - php

crew,
I have a controller_jobs.php in which I have two methods. The index method in which every job from my database that is available is pulled from the DB and assigned to my template, career.html. In the career.html I display every available job through a foreach, this works as intended.
The second method is called show and is called with the primary key from the job.
In my html I got a Button at every job position. The HTML was designed from another company and is still hardcoded with an href call to the second template career-details.html.
How can I manage to call the show() function from the controller on this button and start the next template??
<div class="wu__ltblue--bg eq row--flex row--aic row--jcc">
<a href="career-details.html" class="btn btn-borderd">
<span class="fa-stack">
<i class="fa fa-circle fa-stack-2x icon-background1"></i>
<i class="fa fa-chevron-right fa-stack-1x"></i>
</span> Ansehen</a>
</div>
I was told to use a form to call the method in there, but I'm not certain about how to use it.
Thanks for help in advance.
The example I got was to lookup on things they already did.
<form id="form_reserve" method="post" action="{$SITEURL}payprocess&PHPSESSID={$SID}"> "Buttoncode" </form>
To be honest, i don't understand what they did in there as I am pretty new to webdevelopment.
And these are my functions from the controller.php
public function index() {
$js_array = array();
$jobs = array();
$dbJobs = new DBJobs();
$jobs = $dbJobs->getAll();
$ControllerLibs = new ControllerLibs();
foreach ($jobs as &$job) {
$job['STELLENKURZBESCHREIBUNG'] = $job['STELLENKURZBESCHREIBUNG'];
$job['STELLENBESCHREIBUNG'] = $job['STELLENBESCHREIBUNG'];
$job['PDFDOKUMENT'] = $job['PDFDOKUMENT'];
$job['BILD'] = $job['BILD'];
$job['PK'] = $job['PK'];
$template = $this->template;
$template->assign('JS_FILES', $js_array);
$template->assign('JOBS', $jobs);
$template->display('career.html');
} // Index
public function show($pk) {
$js_array = array();
$jobs = array();
$dbJobs = new DBJobs();
$jobs = $dbJobs->getByPK($pk);
foreach ($jobs as &$job) {
$job['STELLENKURZBESCHREIBUNG'] = $job['STELLENKURZBESCHREIBUNG'];
$job['STELLENBESCHREIBUNG'] = $job['STELLENBESCHREIBUNG'];
$job['PDFDOKUMENT'] = $job['PDFDOKUMENT'];
$job['BILD'] = $job['BILD'];
}
}

Related

foreach assign wrong id to wire model after calling search function again

I have a weird problem with Livewire, I am unable to identify why this is happening.
The Problem is: I have a list populated from foreach loop, and the data in foreach loop comes from the search function. For example, I have two list items on the list, and I update some data on them using the dropdown available, if i update the first item and recall the search function the data is updated and now only one item left in the list but now it is with wrong wire model id, but the data come from search function is correct but livewire assign the wrong id to it.
To understand the issue properly, please watch this short video.
Relevant Codes:
Blade
<div>
#foreach ($this->result as $data)
<div>
<span class="has-float-label" style="width: 190px;">
<select wire:model="list_session_picker.id.{{ $data->id }}" wire:key="sessionList-{{ $data->id }}" required class="form-control">
#foreach ($sessionData as $session)
{{ $this->isDetailsExist ? ($this->list_session_picker['id'][$data->id] = "$data->student_session_id") : null }} {{-- This line of code selects the default value of the item in the database, so t will be sow as selected --}}
<option value="{{ $session->id }}">{{ $session->session }}</option>
#endforeach
</select>
</span>
</div>
</div>
<div>
<button class="btn btn-secondary text-light" wire:click.prevent="promote">
Promote all
</button>
</div>
Componenet
public $result = [], $list_session_picker = [], $selectedItems = [];
public $isDetailsExist = true;
public function search()
{
$search = SchoolStudent::query();
if (!empty($this->search_session_picker && $this->search_class_picker && $this->search_medium_picker)) {
$search->where('student_session_id', $this->search_session_picker);
$search->where('student_class_id', $this->search_class_picker);
$search->where('student_medium', $this->search_medium_picker);
$this->result = $search
->whereNull('date_of_graduate')
->with(['session:id,session', 'class:id,name'])
->get();
}
}
public function resetFields()
{
$this->selectedItems = [];
$this->list_session_picker = [];
$this->result = [];
$this->isDetailsExist = true;
}
public function promote()
{
if (count($this->selectedItems) > 0) {
foreach ($this->selectedItems as $ikey => $sitems) {
if (isset($this->selectedItems[$ikey]) && $this->selectedItems[$ikey] !== false) {
foreach ($this->list_session_picker as $lskey => $session) {
$selectedStudent = SchoolStudent::findOrFail($sitems);
$selectedStudent->student_session_id = $this->list_session_picker[$lskey][$selectedStudent->id];
$selectedStudent->update();
}
unset($session);
}
}
unset($sitems);
$this->resetFields();
$this->search();
}
}
To refresh the list I am calling the search method again with already selected values, but is there any other way please suggest, because if I am not doing the search again, dom is all correct but the updated item has not been removed from the list, but I prefer to call the search function again
Since my comment seems to have solved the issue, I'll leave it as answer so it can be accepted.
Within the video, the dropdown is wrapped in a wire:ignore. This prevents the dropdown from ever getting updated.
Read more about it in the docs.

How can I output the Cart item number?

i was wondering of how can i show how many items i got in the cart? I did a path in the twig but im not sure how to show it.
this is my controller i have the route and in the twig i call the path with the name (count_panier).
/**
* #Route("/count/{qtt}", name="count_panier")
*/
public function testAction($qtt,Request $req)
{
$qtt = $this->afficherCount($req);
return $this->redirectToRoute('mag',['count'=>$qtt]);
}
//----------------------------------------------
public function afficherCount(Request $req){
$sess = $req->getSession();
$panier = $sess->get('panier',[]);
$qtt = 0;
foreach($panier as $item)
{
$qtt += $item->quantiteCommandee;
}
return $qtt;
}
And this is my twig, this is the part of the top navbar
<div class="menu">
<a class="active" href="{{path('mag')}}">Catalogue</a>
Contact
Crée un compte
Connexion
<a href="panier">Panier
<img width="30" alt="img" src="{{asset('images/cart.png')}}"/></a>
<span id='panierCompteur'>
items</span>
</div>
in your Controller you are passing just one parametere count => '$qtt
So in the Twig file, if you want get it, do this:
{{ count }}
So if you want to get a link that shows how many items you have, do like this:
<span id='panierCompteur'>
{{count}}
items</span>
(you are not usign the $qtt variable so don't pass it)
/**
* #Route("/count", name="count_panier")
*/
public function testAction(Request $req)
{
$qtt = $this->afficherCount($req);
return $this->redirectToRoute('mag',['count'=>$qtt]);
}
//----------------------------------------------
private function afficherCount(Request $req){
$sess = $req->getSession();
$panier = $sess->get('panier',[]);
$qtt = 0;
foreach($panier as $item)
{
$qtt += $item->quantiteCommandee;
}
return $qtt;
}
Of course the first time you render this main page you need to run the function afficherCount() in the index Controller (or whatever is your main controller) and return to the main page the count => '$qtt with all your others arguments.
You are redirecting to another route, so you need to "handle" the redirection if you want to get those parameters:
/**
* #Route("/your-route/{count?}", name="mag", requirements={"count"="\d+"})
*/
public function yourFunction(Request $req, $count)
{
// true if is the first time you render this page or if you don't pass the value
if($count === null){
$count = afficherCount($req);
}
return $this->Render('yourTwigFile.html.twig',['count'=>$count]);
}
{count?} : the ? if for optional parameters so the first time you render this page is not necessary to pass the value in the URL
requirements={"count"="\d+"} : the value can only be an integer
(PS. this function is probably your index)
for more information / examples

next/prev month is not working in laravel

So I have this view that shows a table and two buttons (next/prev). Each button has a query string /?date=next that I capture in my controller using request()->has('date').
<a class="button is-primary is-outlined" href="/?date=prev">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next">Next</a>
The user shall be able to go to next month, and the month after that depending on how many times he clicks on the next/prev button.
Initially, I had two approaches. First, I thought to myself that I can use a $count that increments whenever the user clicks the button in $post->whereMonth('date', $this->count). Second, simply use the Carbon library, $post->date->addMonth().
In both approaches, the date remain the same despite the number of times the next/prev button was clicked.
First approach:
class PostsController extends Controller
{
protected $count;
public function __constructor(){
$this->count = 0;
}
public function show(Hour $post){
if(request()->has('date') == 'next'){
$posts = $post->whereMonth('date', $this->count);
$this->count++;
} else if(request()->has('date') == 'prev'){
$posts = $post->whereMonth('date', $this->count);
$this->count++;
}
return view('user.table', compact('posts'));
}
}
Second approach (favorite):
public function show(Hour $post){
if(request()->has('date') == 'next'){
$posts = $post->date->addMonth();
} else if(request()->has('date') == 'prev'){
$posts = $post->date->subMonth();
}
return view('user.table', compact('posts'));
}
I've seen that Laravel provide the query builder increment, but that only work for columns, and not variables.
Is there a way I can make this work by remembering the previous date as shown in the second approach.
Looks like you just want to display a date. In this case, do this:
public function show(Hour $post)
{
$months = request('months', 0);
if (request('date') === 'next'){
$posts = $post->date->addMonth();
$months++;
} elseif(request('date') === 'prev'){
$posts = $post->date->subMonth();
$months--;
}
return view('user.table', compact('posts', 'months'));
}
And in the view:
<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Previous</a>
<a class="button is-primary is-outlined" href="/?date=next&months={{ $months }}">Next</a>

Building a menu system with a PHP class

UPDATE 2 ::
This is the output I am getting from the function right now :
<nav>
<ul> //UL 1
<ul> //UL 2
menu link 1
<li>login</li>
<li>
<ul>sublink3</ul>
</li>
<li><a>menu link 3</a></li>
<li>
<ul>
sublink1
<li>sublink2</li>
</ul>
</li>
<li>menu link 4</li>
<li>menu link 5</li>
<li>
<ul>
sublink5a
<li>sublink5b</li>
<li>sublink5c</li>
<li>sublink5d</li>
</ul>
</li>
</ul> //End of UL 2
<ul></ul> //dont not why this is here?
</ul> //End of UL 1
</nav>
UPDATE
Ok I have re-move the construct, and this is how I am trying to display my menu :
<?php include('./includes/menu.php'); ?>
<h1>HEADER FILE TITLE TEST</h1>
<?php
$build = new Menu;
var_dump($build->DisplayMenu());
?>
I mainly only use CakePHP to build sites with, but I am trying to push my PHP skills up to the next level. So I am looking at other frameworks and OOP (which I have never used within PHP before). So I set myself a little task of building a menu system, controllable from a database e.g. titles and path links come form my db.
This works fine when I just built it has a function put all my menu system items within an array and then used a print call to display the menu, then I just called the function on the page I had required the file to.
But I thought that this was not the best way about doing it, so I wanted to make it a class, so I put a class call around my function, and then changed the print call to a return. What I got form the class/function was a NULL answer when I var dumped it. So I did some research, and re-read a lot about how to declare an array within the magic 'construct' function.
But now I am very confused, should this be inside my Menu function or outside? Just by adding the construct function, it started to display 'string(9)' - which I don't know why? Here is my code :
//Menu Include file
class Menu {
public $testforme = "dfdfdfdf"; //Just a test to see how to call somedata
public function DisplayMenu() {
$DBConn = getConnection(); //Set new database connection
$SQLMainMenu = "SELECT * FROM menu"; //Get Menu setting from database
//$MenuBuild[] = NULL; //Open array for menu to save data into
function __construct($MenuBuild = array()) {
//not sure what to put here???
}
try {
$MenuBuild[] = '<nav><ul>';
//Foreach loop for all main menu links
foreach ($DBConn->query($SQLMainMenu) as $MainMenu) {
$MainMenuID = $MainMenu['id'];
$MainMenuPath = $MainMenu['linkpath'];
$MainMenuSublinkCounts = $MainMenu['sublinks'];
$SQLSubMenu = "SELECT * FROM submenu WHERE menu_id = $MainMenuID";
if ($MainMenuPath == 'NULL') {
$MenuBuild[] = '<li><a>' .$MainMenu['name'] .'</a>';
} else {
$MenuBuild[] = '<li>' .$MainMenu['name'] .'';
}
if ($MainMenuSublinkCounts >=1) { $MenuBuild[] = '<ul>'; }
//Foreach loop to build all inner links for menu
foreach ($DBConn->query($SQLSubMenu) as $SubMenu) {
$SubLinkMenuIDs = $SubMenu['menu_id'];
$SubLinkTitles = $SubMenu['name'];
$SubLinkPaths = $SubMenu['linkpath'];
if ($SubLinkMenuIDs == $MainMenuID) {
$MenuBuild[] = '<li>'. $SubLinkTitles . '</li>'; }
} //End of inner foreach loop
if ($MainMenuSublinkCounts >=1) {
$MenuBuild[] = '</ul>';
}
$MenuBuild[] = '</li>';
} //End of foreach loop
$MenuBuild[] = '</ul></nav>';
//Print the Array that holds the menu.
foreach ($MenuBuild as $MenuKey => $MenuData) {
$MenuSystem = $MenuBuild[$MenuKey]; return $MenuSystem;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
} //End of function DisplayMenu
} //end of class
Now I am connection to my db using a PDO, which is working fine, it within a other file that both are included on.
Please let me know of any good help sites and I have read lots of the questions / answers on here.
Also please go easy on me? this is the 1st time I am using OOP PHP.
If of I am not doing something right, with the way I am building the menu please point at any issues with that :).
Thanks Glenn.
Ok, this is for you, but you really need to do some more research before putting something like this up
my approach encapsulates some functionality but it should seem pretty clear where it's headed just by looking at it. Please feel free to make any questions
(REREedited) includes/menu.php
<?php
class Menu {
private $db;
private $main;
public function __construct($db=null) {
$this->db = $db ? $db : getConnection();
$q = 'SELECT id,name,linkpath,sublinks FROM menu';
$this->main = $this->db->query($q);
}
public function displayMenu() {
$items = array();
foreach ($this->main as $row) {
$path = $row['linkpath'];
$link = self::link($row['name'],$path==='NULL'?null:$path);
// if there is a submenu, concatenate to with the "parent" into the same "item"
if ($row['sublinks'] > 0) $link .= $this->subMenu($row['id']);
$items[] = $link;
}
// returns the whole nav menu.
return '<nav>'.self::lists(array_filter($items)).'</nav>';
}
private function subMenu($id) {
$q = 'SELECT name,linkpath FROM submenu WHERE menu_id = ';
$sub = array();
foreach ($this->db->query($q.$id) as $row) {
$sub[] = self::link($row['name'],$row['linkpath']);
}
return self::lists(array_filter($sub));
}
static function link($content, $href) {
return '<a '.($href?'href="'.$href.'"':'').'>' .$content.'</a>';
}
static function lists(array $items) {
if (!$items) return null;
return '<ul><li>'.implode('</li><li>',$items).'</li></ul>';
}
}
test.php
<?php include('./includes/menu.php'); ?>
<h1>HEADER FILE TITLE TEST</h1>
<?php
try {
$build = new Menu;
echo $build->displayMenu();
} catch (Exception $e) {
echo $e->getMessage().PHP_EOL.$e->getTraceAsString();
}
?>

Zend fetchAll foreach 2 times run dont loop 2nd time;

This is very simple to understand
Image Class
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
public function getList() {
return $this->fetchAll();
}
}?>
My PHP Code
<?php
require 'config.php';
$imgTable = new Image(); // Create Object
$imgList = $imgTable->getList(); // fetch Data
$template = new Template('portfolio'); // Initialize Template and tell which template to pick
$template->imgList = $imgList; // set template variable
$template->render(); // Generate Template output
?>
I can access template variable inside template using $this
Below code is from inside the template
$xback = 0;
foreach ($this->imgList as $images) {
echo 'imageArray[' . $xback . '] = "' . $images['sef'] . '";';
$xback++;
}
?>
.......
<?php
foreach ($this->imgList as $images) {
?>
<div class="portfolio_item">
<img src="<?php echo PATH_WEB . $images['image_thumb'] ?>" height="146" width="209" />
<div class="title"><?php echo $images['image_title'] ?></div>
<div class="right link">
View Details
</div>
</div>
<?php
}
?>
Above code is working fine, but below some few lines, I have to iterate over the same data again dont output any thing. If I comment the first one, 2nd starts working.
First one is to create the JS array and is in head section,
Second part is in HTML to display images
I hope its a pointer issue, I may have to set the loop current item to start, but I am not understanding it right now .... reset($this->imgList) didnt worked
please help
I think it has something to do with the fetchAll call, try this:
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
protected $images;
public function getList() {
// Employ lazy loading pattern to load images if they aren't set yet
if (!isset($this->$images)) {
$this->images = $this->fetchAll();
}
return $this->images;
}
}?>

Categories