CI-4 how to show multiple tables in one page - codeigniter-4

good day all,
since i'm new in Code Igniter 4 (i was a native PHP self-learner) and i'm new in MVC, my question is how can i show multiple tables in one page ?
i have a dashboard view with 2 tables inside. one is for display students data and the other is for teachers data. there is no relation between tables, so i can't join the tables.
i have successfully show one of the table (student or teacher) but i can't show both tables in dashboard at once. i think i have to pass 2 models into controller function but i just can't figure it out how to do it.
any help will be appreciated
here is parts of my codes (successfully showing data from 1 table) :
Controller
use App\Models\mStudent;
class Admin extends BaseController
{
public function index()
{
$model = new mStudent();
$data['title'] = 'Students';
$data['getStudents'] = $model->getStudents();
echo view('admin/header', $data);
echo view('admin/top_menu');
echo view('admin/side_menu');
echo view('admin/dashboard', $data);
echo view('admin/footer');
}
Model
public function getStudents()
{
return $this->findAll();
}
public function getTeachers()
{
return $this->findAll();
}
View
<!-- students table-->
<table class="table table-bordered text-sm">
<thead>
<tr>
<th style="width: 10px; text-align: center;">No</th>
<th style="text-align: center;">NAME</th>
<th style="text-align: center;">Class</th>
</tr>
</thead>
<tbody>
<?php $no = 1;
foreach ($getStudents as $students) { ?>
<tr>
<td><?= $no; ?></td>
<td><?= $students['name'] ?></td>
<td><?= $students['class'] ?></td>
</tr>
<?php $no++;
} ?>
</tbody>
</table>
<!-- teacher table-->
<table class="table table-bordered text-sm" id="defaulttable">
<thead>
<tr>
<th style="width: 10px; text-align: center;">No</th>
<th style="text-align: center;">NAME</th>
<th style="text-align: center;">ID</th>
</tr>
</thead>
<tbody>
<?php $no = 1;
foreach ($getTeachers as $teachers) { ?>
<tr>
<td><?= $no; ?></td>
<td><?= $teachers['name'] ?></td>
<td><?= $teachers['id'] ?></td>
</tr>
<?php $no++;
} ?>
</tbody>
</table>

Adding Dynamic Data to the View
In your Controller, right below $data['getStudents'] = $model->getStudents(); add:
$data['getTeachers'] = $model->getTeachers();
Addendum
Then in your model, return the respective result sets. I.e:
Model
public function getStudents()
{
return $this->db->table("students")->get()->getResultArray();
}
public function getTeachers()
{
return $this->db->table("teachers")->get()->getResultArray();
}

this is what i looking for
Controller
use App\Models\mStudent;
use App\Models\mTeacher;
class Admin extends BaseController
{
public function index()
{
$model_student = new mStudent();
$model_teacher = new mTeacher();
$data = array(
'student' => $model_student->getStudents(),
'teacher' => $model_teacher->getTeachers()
);
echo view('admin/header');
echo view('admin/top_menu');
echo view('admin/side_menu');
echo view('admin/dashboard', $data);
echo view('admin/footer');
}
View
Students :
<select name="stdid">
<?php foreach ($student as $std) : ?>
<option value="<?= $std['stdid']; ?>"><?= $std['stdname']; ?></option>
<?php endforeach; ?>
</select>
Teachers :
<select name="tcrid">
<?php foreach ($teacher as $tcr) : ?>
<option value="<?= $tcr['tcrid']; ?>"><?= $tcr['tcrname']; ?></option>
<?php endforeach; ?>
</select>
hope this will help someone out there

Related

How to use other classes object in .phtml file without object manager in magento 2

I am currently invoking the method “xyz” using the object manager, however the object manager should not be used in phtml file as mentioned in the Magento 2 documentation. What is the best practice to create an object of other classes in phtml file?
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
ViewModel files can be used to add codes in a template file without using an object manager.
Here Are Steps to create View Model
Step 1:- Create a layout file in Vendor/Module/view/frontend/layout/custom_index_custom.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block name="dummy" template="Sunarc_Custom::details.phtml">
<arguments>
<argument name="view_model" xsi:type="object">Sunarc\Custom\ViewModel\Customer</argument>
</arguments>
</block>
</referenceContainer>
</body>
</page>
Step 2:- Create a view model file under Vendor/Module/ViewModel/Customer.php
<?php
$viewModel = $block->getViewModel();
$collection = $viewModel->getCollection();
if ($collection->count()) {
?>
<div class="table-wrapper customer">
<table class="data table" id="my-custom-table">
<thead>
<tr>
<th scope="col" class="col id"><?php echo __('ID') ?></th>
<th scope="col" class="col name"><?php echo __('Name') ?></th>
<th scope="col" class="col email"><?php echo __('Email') ?></th>
</tr>
</thead>
<tbody>
<?php
foreach ($collection as $item) : ?>
<tr>
<td data-th="<?= $block->escapeHtml(__('ID')) ?>" class="col id">
<?php echo $item->getId() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Name')) ?>" class="col name">
<?php echo $item->getName() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Email')) ?>" class="col email">
<?php echo $item->getEmail() ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
?>
Step 3:- Create your custom phtml file in Vendor/Module/view/frontend/templates/details.php
<?php
$viewModel = $block->getViewModel();
$collection = $viewModel->getCollection();
if ($collection->count()) {
?>
<div class="table-wrapper customer">
<table class="data table" id="my-custom-table">
<thead>
<tr>
<th scope="col" class="col id"><?php echo __('ID') ?></th>
<th scope="col" class="col name"><?php echo __('Name') ?></th>
<th scope="col" class="col email"><?php echo __('Email') ?></th>
</tr>
</thead>
<tbody>
<?php
foreach ($collection as $item) : ?>
<tr>
<td data-th="<?= $block->escapeHtml(__('ID')) ?>" class="col id">
<?php echo $item->getId() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Name')) ?>" class="col name">
<?php echo $item->getName() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Email')) ?>" class="col email">
<?php echo $item->getEmail() ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
?>
One can also use Block Files to do the same.

how to add simple searching yii2

I have to make a simple searching in my index view.
The data to be searched in the table is not a grid view but a regular table.
How can I add a simple searching like this?
And this is the code in index view
Search
<table class="table table-striped table-bordered">
<tr>
<th class="text-center">NIP</th>
<th class="text-center">Nama Pegawai</th>
<th class="text-center">Jumlah Dokumen</th>
<th></th>
</tr>
<?php foreach($models as $data): ?>
<tr>
<td><?= $data["nip"] ?></td>
<td><?= $data["nama"] ?></td>
<td align = "center"><?= $data["jumlah"] ?></td>
<td width = "200 px" align = "center"><a class = "btn btn-success" href = "./?r=arsip-sdm/detail&id=<?= $data['nip'] ?>">Detail</td>
</tr>
<?php endforeach; ?>
</table>
And this is the code in controller
help me please
You could use a separate filter form
eg :
<div class="post-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'creation_date') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
perform a render partial in your view and use the normal 'searchModel' => $searchModel, in your you gridView config
you can see some sample here
http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html
http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#filtering-data
http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#separate-filter-form

ZF2 module title in layout

I'm having trouble with my layout and viewModel
My design requires that the title set in my viewModel, eg 'blog categories' to be pushed to the layout.
I'm using $this->headTitle() to set the title of the page but i can't get it anywhere else.
because of a lot of changes in the layout per page, i have been forced to use partial in the layout.
single.phtml
<?php echo $this->partial('lendstudy/partial/basic/top'); ?>
<div class="container_12 clearfix">
<div id="content_wrapper">
<?= $this->partial('lendstudy/partial/basic/title'); ?>
<?php echo $this->content; ?>
<?= $this->partial('lendstudy/partial/sidebar/left'); ?>
</div>
</div>
<?php echo $this->partial('lendstudy/partial/basic/bottom');
I'm setting the header title in the view
index.phtml from category in a blog module
<?php
$title = $this->translate('Categories');
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<p>Add new category</p>
<table class="table table-bordered table-hover">
<tr>
<th>Category</th>
<th> </th>
<th> </th>
</tr>
<?php foreach($categories as $category) : ?>
<tr>
<td><?php echo $this->escapeHtml($category->getName());?></td>
<td>
[Edit]
</td>
<td>
[Delete]
</td>
</tr>
<?php endforeach; ?>
</table>
it would then need to be outputtet in the partial/basic/title.
title.phtml
<div class="grid_12 page_title">
<h1><?= $this->headTitle(); ?><span class="subtitle"><?= $this->translate('More information about the Lend Study association') ?></span></h1>
<div class="page_navigation">
<?php $partial = array('lendstudy/partial/basic/breadcrumbs', 'default') ?>
<?php $this->navigation('navigation')->breadcrumbs()->setPartial($partial) ?>
<?php echo $this->navigation('navigation')->breadcrumbs()->render() ?>
</div>
</div>
how do i do this?

Snippet not working in MODx

I've got a snippet in my ModX Evo. The problem is that on my local this shippet is working ok,but when I upload it to the host it returns only blank space. The code is a mess, but I need to get figured that out. Any ideas?Thx.
<?php
$action=$_GET['action'];
switch ($action){
case('add'):_add();break;
case('view'):_view();break;
case('order'):_order();break;
case('del'):_del();break;
}
/////////////////////////////////////////////////////////////////
function _add()
{
global $modx;
session_start();
if(!session_is_registered('things')){session_register('things');}
$ar=$_SESSION['things'];
$ar_size=sizeof($ar)-1;
$break=false;
$i=0;
if($ar_size>=0)
{
while ($i<=$ar_size):
$buf=$ar[$i];
if($buf['id']==$_GET['thing']){$_SESSION['things'][$i]['count']=$buf['count']+1;$break=true;}
$i++;
endwhile;
}
if($break==false){
$_SESSION['things'][($i)]=array('title' => $_GET['title'],
'id'=>$_GET['thing'],
'price'=>$_GET['price'],
'count'=>1);}
$modx->sendRedirect("/index.php?id=".$_GET['return']);
}
function _view()
{
if (!isset($_GET['zakaz'])){
session_start();
if(!session_is_registered('things')){session_register('things');}
if (isset($_GET['del']))
{
$buf=array();
$ar=$_SESSION['things'];
$ar_size=sizeof($ar)-1;
if($ar_size>=0)
{
$i=0;
while ($i<=$ar_size):
if(($i+1)!=$_GET['del']){$buf[sizeof($buf)]=$ar[$i];}
$i++;
endwhile;
}
$_SESSION['things']=$buf;
}
if (isset($_GET['delall']))
{
$_SESSION['things']=array();
}
if (isset($_GET['cn']))
{
$c=$_GET['cn'];
$ar=$_SESSION['things'];
$ar_size=sizeof($ar)-1;
if($ar_size>=0)
{
$i=0;
while ($i<=$ar_size):
$b=(int)$c[$i];
if($b>0)
{
$ar[$i]['count']=$b;
}else{$ar[$i]['count']=1;}
$i++;
endwhile;
}
$_SESSION['things']=$ar;
}
if((isset($_GET['peresh']))or(isset($_GET['del']))or(isset($_GET['delall'])))
{
global $modx;
$modx->sendRedirect("/index.php?id=10&action=view");
}
?>
<form action='index.php' method='GET'>
<input type="hidden" value="10" name="id">
<input type="hidden" name="action" value="view">
<table border=0 cellpadding=4 cellspacing=2 width='100%'>
<tr align='center'>
<td align=center colspan=5 bgcolor='#c5dcf8' class='table_title'>Ваша корзина</td>
</tr>
<tr align='center'>
<td bgcolor='#c5dcf8'>№</td>
<td bgcolor='#c5dcf8' >наименование товара</td>
<td bgcolor='#c5dcf8'><nobr>цена, руб.</nobr></td>
<td bgcolor='#c5dcf8'>кол-во</td>
<td bgcolor='#c5dcf8'>удалить</td>
</tr>
<?php
$ar=$_SESSION['things'];
$ar_size=sizeof($ar)-1;
$break=false;
$i=0;
if($ar_size>=0)
{
$summ=0;
while ($i<=$ar_size):
$buf=$ar[$i];
$i1=$i;
$i++;
$name=$buf['title'];
$id=$buf['id'];
$price=$buf['price']*$buf['count'];
$summ=$summ+$price;
$count=$buf['count'];
echo"<tr><td bgcolor=\"white\" style=\"color:black;\" align=\"center\">$i</td><td bgcolor=\"white\"style=\"color:black;\" align=\"center\">
<a style=\"color:blue\" href=\"/index.php?id=$id\">$name</td><td bgcolor=\"white\"style=\"color:black;\" align=\"center\">$price</td>
<td bgcolor=\"white\" style=\"color:black;\" align=\"center\"><input type=\"edit\" name=\"cn[$i1]\" value=\"$count\"SIZE=\"4\"></td>
<td bgcolor=\"white\" style=\"color:black;\" align=\"center\"><font color=\"Maroon\" style=\"color:Maroon;font-weight:bold;font-size:16px;text-decoration:none;\">X</td></tr>";
endwhile;
?>
<tr><td colspan="2" align="right" bgcolor="white"><b style="color:navy">Итого к оплате:</td><td style="color:blue;"bgcolor="white" align="center"><?php echo $summ; ?></td><td align="center"><input name="peresh" style="font-size:10px" type="submit" value="Пересчитать"></td><td align="center"><input style="font-size:10px" name="delall" type="submit" onclick="return confirm('Вы согласны?')" value="Удалить все">
</table><br><center><input type="submit" name="zakaz" value="Оформить заказ"></center></form>
<?php
}
else
{
?>
<tr><td colspan="5" align="center" valign="middle" height="60" style="color:blue" bgcolor="white">Корзина пуста</td></tr>
</table></form>
<?php
}
}
else
{
//////////////////////для заказа////////////////////////
}
?>
<?php
}
You should put all your functions in:
If (!function_exists('yourfunction')) {
[....]
EDIT: does your snippet work in a local modx install? Or does it work as a normal php-script? I dont think you can stop/start php (?> and
You could check your error-log within Modx. If it displays blank errors might be turned off
session_register() and session_is_registered() are deprecated in PHP 5.3 and removed in PHP 5.4, according to the docs. I'd definitely take that out.
As OptimusCrime says, you can't use <?php and ?> in snippets; the ENTIRE snippet will be evaluated in parse time and doing that results in parse errors. May find some evidence of that in the error log.
Also all the references to session_start really shouldn't be there - MODX handles the sessions for you and you should not be re-starting them again. I'm not sure if that will cause issues, but if anything it can help to clear up your code even just a tiny bit ;)

pagination content

I am trying to do pagination for my forum. I am trying to get the results to show from the db, although everything is everywhere.
here is my code:
<!-- start with the table -->
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td width="53%" align="center" bgcolor="#E6E6E6" style="padding:5px;"><strong>Topic / Thread Starter</strong></td>
<td width="15%" align="center" bgcolor="#E6E6E6" style="padding:5px;"><strong>Replies/Views</strong></td>
<td width="13%" align="center" bgcolor="#E6E6E6" style="padding:5px;"><strong>Last Post By</strong></td>
</tr>
<div id="p1" class="pagedemo _current" style="">
<?php
$sql="SELECT * FROM forum ORDER BY datetime DESC";
$result=mysql_query($sql);
$i = 1;
$z = 1;
while($rows = mysql_fetch_array($result)){ // Start looping table row
if(($i % 4) != 0)
{ ?>
<tr>
<td bgcolor="#FFFFFF" style="padding:5px;"><a class="normal" href="view_topic.php?id=<? echo $rows['id']; ?>"><? echo $rows['topic']; ?></a><br /><span style="color:#666; font-size:12px;">Started By <?php echo "<a class='normal' href='http://www.example.com/view_profile.php?user=".getID($rows[username])."'>"; ?> <? echo $rows['username']; ?></a></span></td>
<td align="center" bgcolor="#FFFFFF">Replies: <? echo $rows['reply']; ?><br />Views: <? echo $rows['view']; ?></td>
<td align="center" background="http://example.com/images/forum_fade_bckg.png"><span style="color:#666; font-size:12px;">
<?php echo "<a class='normal' href='http://www.example.com/view_profile.php?user=".getID($rows[lastPoster])."'>"; ?> <?php echo $rows['lastPoster']; ?></a><br /><?php $date = substr($rows['datetime'],0,12);
if($date == date("M d, Y")) {
echo "Today, " . substr($rows['datetime'],-8);
} else {
echo $rows['datetime'];
}?> </span></td>
</tr>
<?php
// do whatever for the page... (this is inside the div)
$message = $row['message'];
echo $i . " " . $message. "<br>";
$i+=1;
}
else
{
$z+=1;
// GET ONLY NUMBERS HERE THAT ARE DIVISIBLE BY 4!!!!
// this is the end of the starting page, and the begining of the next page
echo '<br>---end---</div>
<div id="p'.$z.'" class="pagedemo" style="display:none;">---start---<br>NEXT PAGE!!!!!!!'; //
}
}
?>
</div>
The results, instead of staying in the div, are actually below the div. when I take out everything b/w the <tr> and </tr>, it all fits into the div. What am I doing wrong?
If you view the source of the page the issue should be apparent. I see a few mistakes that could be the problem.
The TABLE at the top of the snippet ends the TR tag then a DIV starts. A DIV should only reside within a TD, TH or outside the TABLE. Also in the snippet you provided there is no ending table tag. With all the other issues that is probably the one that is messing the browser up.
Please adjust structure to be similar to this:
<div>...</div>
<table>
<tr>
<td>Some tags in here(A, DIV, SPAN, etc.)</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
</table>
<div>...</div>
Also it would be worthwhile to migrate certain attributes to css properties in the style tag. For example the background, bgcolor, align, and width attributes in your snippet.
Sorry if that does not fix the issue its hard to debug without being able to see the issue.

Resources