What is below is my code of search engine on the website. Right now is only searching what is refered as ProductName and ProductNumber. I didn't know what need to be changed to searching whole ProductDescription
Here is Search.php file
protected $_index;
protected $_indexed = array();
/**
*
* #var Zend_Http_Client
*/
protected $_httpClient;
public function __construct()
{
try {
$indexDir = realpath($_SERVER['DOCUMENT_ROOT'] . '/../tmp/search');
$this->_index = Zend_Search_Lucene::open($indexDir);
} catch (Zend_Search_Lucene_Exception $e) {
$this->_index = Zend_Search_Lucene::create($indexDir);
}
$this->_httpClient = new Zend_Http_Client();
$this->_httpClient->setConfig(array('timeout' => 10));
Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
}
public function indexUrl($url)
{
if (is_array($url)) {
foreach ($url as $uri) {
$this->_indexUrl($uri);
}
} else if (is_string($url)) {
$this->_indexUrl($url);
}
}
public function indexWholePage()
{
$pageUrl = $this->_getHostName();
$this->_indexUrl($pageUrl . '/');
}
protected function _indexUrl($url)
{
if (in_array($url, $this->_indexed))
return;
$log = Zend_Registry::get('Zend_Log');
$log->log($url, Zend_Log::NOTICE);
$this->_httpClient->setUri($url);
$response = $this->_httpClient->request();
$this->_indexed[] = $url;
if ($response->isSuccessful()) {
$body = $response->getBody();
$doc = Zend_Search_Lucene_Document_Html::loadHTML($body, true);
foreach ($doc->getLinks() as $link) {
if ($this->_isValidPageLink($link) && !in_array($this->_getHostName() . $link, $this->_indexed)) {
$this->_indexUrl($this->_getHostName() . $link);
}
}
$t = new Zend_Search_Lucene_Index_Term($url, 'url');
$q = new Zend_Search_Lucene_Search_Query_Term($t);
$hits = $this->_index->find($q);
foreach ($hits as $hit) {
if ($hit->md5 == md5($body)) {
return;
} else {
$this->_index->delete($hit->id);
}
}
$doc->addField(Zend_Search_Lucene_Field::Keyword('url', $url));
$doc->addField(Zend_Search_Lucene_Field::UnIndexed('md5', md5($body)));
$this->_index->addDocument($doc);
$log = Zend_Registry::get('Zend_Log');
$log->log('done', Zend_Log::NOTICE);
}
}
public function search($query)
{
return $this->_index->find($query);
}
public function deleteIndex()
{
}
protected function _getHostName()
{
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== "off") ? 'https' : 'http';
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
$uri = $proto . '://' . $host;
if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) {
$uri .= ':' . $port;
}
return $uri;
}
protected function _isValidPageLink($url)
{
$hostName = $this->_getHostName();
if (substr($url, 0, strlen($hostName)) == $hostName ||
substr($url, 0, 1) == '/' || substr($url, 0, 1) == '?') {
if (#preg_match('#^(.+)\.(jpg|gif|png|pdf|doc|xls)$#i', $url)) {
return false;
}
return true;
}
return false;
}
And here is php form to generate search results. Lucene implementations that I found after searching where completly different than what here is. This is my first time with ZendFramework.
<form method="get" action="/search.html" class="searchForm" enctype="application/x-www-form-urlencoded" id="searchForm">
<fieldset>
<input type="text" id="search_text" name="q" value="<?php echo $this->escape($this->query) ?>"><br>
<input type="submit" value="search" id="search" name="search">
</fieldset>
</form>
<h1>Search results</h1>
<?php if(empty($this->searchString)): ?>
<p><strong>Please write text of minimal lenght of<?php echo $this->minimumLength ?></strong></p>
<?php else: ?>
<?php if(count($this->products)){ ?>
<?php foreach ($this->products as $product): ?>
<?php $link = '/'.$this->permalink($product->product_name).','.$product->product_id.','.$product->category_id.',p.html'; ?>
<div class="productlist clearfix">
<a href="<?= $link; ?>" class="clearfix">
<div class="txt">
<h2><?= $product->product_name ?><?php if(strlen($product->product_number) > 2){ echo '<small> [ '.$product->product_number.' ]</small>'; } ?></h2>
<p><?= stripslashes($product->product_intro2) ?></p>
</div>
<div class="pic">
<?php if($product->has_media): ?>
<?php echo $this->thumb($product->media_src, 110, 110) ?>
<?php endif; ?>
<p style="text-align: center;">More</p>
</div>
</a>
</div>
<hr/>
<?php endforeach; ?>
<?php }else{ ?>
<p>0 product was found</p>
<?php } ?>
<div style="clear: both;">
<?php echo $this->products; ?>
</div>
<?php endif ?>
Related
I have a problem with my code. I'am trying to realize a simple blog. Displaying the list of all the posts works. But when I click on a specific post the page of this post doesn't work.
This is the structure of my folder
Here is my index.php
<?php
require_once('controleurs/Controleur.php');
require_once('modeles/Modele.php');
require_once('modeles/Photo.php');
require_once('modeles/Photos.php');
$controleur = new Controleur();
if (isset($_GET['page']) && 'photo' === $_GET['page']) {
$controleur->afficherPhoto();
} else {
$controleur->listerPhotos();
}
Here is my Controleur.php :
class Controleur
{
public function listerPhotos()
{
$photos = new Photos();
$photos = $photos->listerPhotos();
require_once('vues/liste-photos.php');
}
public function afficherPhoto()
{
$photo = new Photo();
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$photo = $photo->afficherPhoto($_GET['id']);
}
require_once('vues/affiche-photo.php');
}
}
Here is class Photo.php
class Photo
{
use Modele;
private $id;
private $fichier;
private $titre;
public function afficherPhoto($id)
{
if (!is_null($this->pdo)) {
$stmt = $this->pdo->prepare('SELECT * FROM photo WHERE id = ?');
}
$photo = null;
if ($stmt->execute([$id])) {
$photo = $stmt->fetchObject('Photo');
if(!is_object($photo)) {
$photo = null;
}
}
return $photo;
}
public function getId()
{
return $this->id;
}
public function getFichier()
{
return $this->fichier;
}
public function getTitre()
{
return $this->titre;
}
}
Here is my liste-photos.php (it works!)
<?php
$titre = 'Mon book';
ob_start();
?>
<article>
<?php foreach ($photos as $photo): ?>
<a href="photo.php?id=<?= $photo->getId() ?>">
<img src="photos/<?= $photo->getFichier() ?>" width="250"/>
</a>
<h2><?= $photo->getTitre() ?></h2>
<?php endforeach; ?>
</article>
<?php
$contenu = ob_get_clean();
require_once('layout.php');
Here is my affiche-photo.php (it doesn't works!) :
$titre = 'Une photo de mon book';
if (is_null($photo)):
$contenu = "Cette photo n'existe pas.";
else:
ob_start();
?>
<article>
<img src="photos/<?php $photo->getFichier(); ?>" width="500" />
<h2><?php $photo->getTitre(); ?></h2>
</article>
<?php
$contenu = ob_get_clean();
endif;
require_once('layout.php');
Thank you if you can help!!!
The main reason why you didn't see the result is because you didn't print the values. You've used <?php $value ?> instead of <?php echo $value; ?>.
Also, according to the official documentation within fetchObject
class Photo
{
use Modele;
private $id, $fichier, $titre;
private function __construct () {}
public function afficherPhoto($id)
{
if (!is_null($this->pdo)) {
$stmt = $this->pdo->prepare('SELECT * FROM photo WHERE id = ?');
if ($stmt->execute([$id])) {
return $stmt->fetchObject(__CLASS__);
}
}
return null;
}
}
In Controller method:
public function afficherPhoto()
{
$photo_cl = new Photo();
$photo = null;
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$photo = $photo_cl->afficherPhoto((int)$_GET['id']);
}
require_once('vues/affiche-photo.php');
}
In the view file affiche-photo.php (fichier and titre must correspond to the DB table field names):
<article>
<img src="photos/<?= $photo->fichier; ?>" width="500" />
<h2><?= $photo->titre; ?></h2>
</article>
Thanks
The problem was indeed with the echo. I finally just change my affiche-photo.php :
<?php
$titre = 'Une photo de mon book';
if (is_null($photo)):
$contenu = "Cette photo n'existe pas.";
else:
ob_start();
?>
<article>
<img src="photos/<?php echo $photo->getFichier(); ?>" width="500" />
<h2><?php echo $photo->getTitre(); ?></h2>
</article>
<?php
$contenu = ob_get_clean();
endif;
require_once('layout.php');
and my liste-photos.php where I changed the path in the href :
<?php
$titre = 'Mon book';
ob_start();
?>
<article>
<?php foreach ($photos as $photo): ?>
<a href="?id=<?= $photo->getId() ?>">
<img src="photos/<?= $photo->getFichier() ?>" width="250"/>
</a>
<h2><?= $photo->getTitre() ?></h2>
<?php endforeach; ?>
</article>
<?php
$contenu = ob_get_clean();
require_once('layout.php');
I am creating a website with MVC architecture and without framework. There are comments like in a blog. I would like to be possible to answer to a comment. But the answer functionnality does not work (when I wanna answer a comment, it is the same as a first comment) and I have difficulties finding why? Could you help me? Here is the adress of the website : cedricjager.com/stream
Here is connection.php:
class Connection {
// Connection
private function getBdd() {
try {
$bdd = ConfigDB::database();
$pdo = new PDO("mysql:host={$bdd['host']}; dbname={$bdd['db_name']}", "{$bdd['username']}", "{$bdd['password']}");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $pdo;
}
// Query
public function query($sql, $params = array(), $fetch = null) {
try {
$req = self::getBdd()->prepare($sql);
$req->execute($params);
if ($fetch == 'one') {
return $req->fetch();
} else if ($fetch == 'all') {
return $req->fetchAll();
} else {
return $req;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Here is the model :
<?php
require_once 'Connection.php';
class Critics extends Connection{
//Récupère les critiques selon l'id de l'article.
public function findAllById($post_id) {
$sql = "SELECT *, DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date
FROM critics
WHERE id_movie = ?";
$params = [$post_id];
$comms = $this->query($sql,$params,'all');
$critics_by_id = [];
foreach ($comms as $comm) {
$critics_by_id[$comm['id']] = $comm;
}
return $critics_by_id;
}
//Récupèrer les critiques qui ont des enfants.
public function findAllWithChildren($post_id, $unset_children = true) {
$comms = $critics_by_id = $this->findAllById($post_id);
foreach ($comms as $id => $comm) {
if ($comm['parent_id'] != 0) {
$critics_by_id[$comm->parent_id]->children[] = $comm;
if ($unset_children) {
unset($comms[$id]);
}
}
}
return $comms;
}
//récupèrer une critique signalée.
public function findCritics() {
$sql = "SELECT *,DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date FROM critics WHERE report=1";
$req = $this->query($sql);
return $req;
}
public function noCritic() {
if ($this->findCritics() == false) {
$msg = '<div class="alert alert-warning">Il n\'y a pas de critiques signalées.</div>';
return $msg;
}
}
//insérer une critique.
public function insertCritic(){
if(isset($_POST['content']) && !empty($_POST['content'])){
$parent_id = isset($_POST['parent_id']) ? $_POST['parent_id'] : 0;
$depth = 0;
if ($parent_id != 0){
$sql = 'SELECT id, depth FROM critics WHERE id = ?';
$params = [$parent_id];
$comm = $this->query($sql,$params, 'one');
if ($comm == false) {
throw new Exception("Ce parent n'existe pas");
}
$depth = $comm->depth + 1;
}
if ($depth >= 3) {
echo "Impossible de rajouter une critique";
}
else {
$sql = 'INSERT INTO critics SET content = ?, author = ?, id_movie = ?, parent_id = ?, date = NOW(), depth = ?';
$params = array($_POST['content'], $_POST['nom'], $_GET['id'], $parent_id, $depth);
$req = $this->query($sql,$params);
}
}
}
}
}
Controller :
public function single() {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$msg = $this->comment->reportCritic();
$this->comment->insertCritic();
$critics = $this->comment->findAllWithChildren($_GET['id']);
$view = require 'Views/single.php';
} else {
header('Location:index.php?p=404');
}
}
Views
<div class="sectioncomments" id="comments">
<?php foreach($critics as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div id="form-comment" class=" panel panel-default formComment">
<div class="panel panel-heading">
<h4>Poster une critique</h4>
<br>
<span class="return"></span>
</div>
<div class="panel panel-body">
<form method="post" class="form-group form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<input type="text" class="form-control" id="nom" placeholder="Votre nom..." name="nom">
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<textarea class="form-control" id="content" placeholder="Votre critique..." name="content"></textarea>
</div>
</div>
<p class="text-right"><button type="submit" class="btn btn-success">Publier</button></p>
<input type="hidden" name="parent_id" id="parent_id" value="0" >
</form>
</div>
</div>
</div>
</div>
</div>
Comments.php
<div id="comment-<?= $critic['id'] ?>">
<p>
<b><?= $critic['author'] ?></b>
<span class="text-muted">le <?= $critic['date'] ?></span>
</p>
<div class="blockquote">
<blockquote>
<?= htmlentities($critic['content']) ?>
</blockquote>
</div>
<div class="formulaire">
<form class="form-group" method="post">
<p class="text-left">
<input type="hidden" name="valeur" value="<?= $critic['id_movie'] ?>">
<input type="hidden" name="idval" value="<?= $critic['id'] ?>">
<?php if($critic['depth'] <= 1): ?>
<button type="button" class="reply btn btn-default" data-id="<?= $critic['id'] ?>"><i class="fas fa-comments"></i></button>
<?php endif; ?>
<button type="submit" name="signal" class="btn btn-default"><i class="fas fa-bolt"></i></span></button>
</p>
</form>
</div>
</div>
<div id="answer">
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
First, I believe that you never set the children index mentionned in your 'comment.php' view :
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
Then you should not call two time in a row findAllById for perfomances purpose.
If I where you, maybe I fetch all One time and then build a tree based on what data you get from your query. It allow you to get an infinite nested comments capabilities.
You can do it this way :
$critics = $this->getAllById($id);//movie id
$childs = []; //Will contain all childs indexed by parent_id
$index = []; //will contain all root critics (no parent)
foreach($critics as &$v){
if($v['parent_id'] === 0){ //if no parent, then add to $index
$indexes[$v['id']] = $v;
} else{ //else create an array in $childs at index parent_id
if(!isset($childs[$v['parent_id']])) $childs[$v['parent_id']] = [];
$childs[$v['parent_id']][] = $v;
}
}
//Then you can build your result :
foreach($childs as $id=>&$child){
$parent= $index[$id] ?? $child[$id] ?? null; // search for the parent of the current child
if(is_null($parent)) continue; // a parent doesn't exists anymore, we ignor it, but you can throw an exception instead
if(!isset($parent['children'])) $parent['children'] = [];
$parent['children'][] = $child;
}
return $index;
Now critic should have a 'children' index where are listed all childs. It allow you to build a tree of comments without limit.
All you have to keep in mind, is to correctly set the parent_id when post a new comment.
Let me know if it solves your problem.
I've been developing in PHP for a few years, but one thing I constantly question is whether I should structure my pages like so:
if(getValue('action') == "jobsFilter" && getValue('jobType') == "open")
{
$job->FetchJobs($jobStatus = 1);
foreach($job->result AS $pulledJob)
{
?>
<div class = "openJob panelJob col-xs-12">
<h2><?php echo $pulledJob['jobTitle'] ?></h2>
View Job
</div>
<?php
}
}else if(getValue('action') == "jobsFilter" && getValue('jobType') == "active")
{
$job->fetchAllJobsAppliedToUser($jobStatus = 1);
foreach($job->result AS $pulledJob)
{
?>
<div class = "openJob panelJob col-xs-12">
<h2><?php echo $pulledJob['jobTitle'] ?></h2>
View Details
</div>
<?php
}
}else if(getValue('action') == "viewJob" && isset($_GET['jobId']))
{
$job->FetchJobs($jobStatus = 1, $jobId = $_GET['jobId']);
foreach($job->result AS $pulledJob)
{
?>
<div class = "viewJob panelJob col-xs-12">
<div class = "pulledJobInfo">
<h2><?php echo $pulledJob['jobTitle'] ?></h2>
<p><?php echo $pulledJob['JobDescription'] ?></p>
</div>
<form method = "post" action = "?action=acceptJob">
<input type = "submit" name = "acceptJobSubmitBtn" class = "acceptJobBtn fullWidthButton ctaButton" value = "Let me help" />
<input type = "hidden" name = "jobId" value = "<?php echo $pulledJob['Id'] ?>" />
</form>
</div>
<?php
}
}
Or whether I should have a separate page, called open-jobs.php for open jobs, closed-jobs.php for closed jobs, etc.
If someone could shed some light on the best solution, that'd be great!
Option A:
if(getValue('action') == "jobsFilter" && getValue('jobType') == "open")
{
$job->FetchJobs($jobStatus = 1);
$file="view1"
}else if(getValue('action') == "jobsFilter" && getValue('jobType') == "active")
{
$job->fetchAllJobsAppliedToUser($jobStatus = 1);
$file="view2"
}else if(getValue('action') == "viewJob" && isset($_GET['jobId']))
{
$job->FetchJobs($jobStatus = 1, $jobId = $_GET['jobId']);
$file="view3"
}
if($job != null){
foreach($job->result AS $pulledJob)
{
include($file)
}
}
Option B:
// Logic what to display
switch(getValue('action')){
case "jobsFilter":
switch (getValue('jobType')){
case "open":
$job->FetchJobs($jobStatus = 1);
$file="view1"
break;
case "active":
$job->fetchAllJobsAppliedToUser($jobStatus = 1);
$file="view2"
break;
}
case "viewJob":
$job->FetchJobs($jobStatus = 1, $jobId = $_GET['jobId']);
$file="view3"
break;
}
// Execute the display
if($job != null){
foreach($job->result AS $pulledJob)
{
include($file)
}
}
I know there were some questions related to this, but there are c ++ or other languages. I get this error and I'm not sure what's wrong with my function.
This is my Error
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Admincategory::deletecategory(), 0 passed in F:\xampp\htdocs\digikalamvc\core\app.php on line 34 and exactly 1 expected in F:\xampp\htdocs\digikalamvc\controllers\admincategory.php:50 Stack trace: #0 F:\xampp\htdocs\digikalamvc\core\app.php(34): Admincategory->deletecategory() #1 F:\xampp\htdocs\digikalamvc\index.php(6): App->__construct() #2 {main} thrown in F:\xampp\htdocs\digikalamvc\controllers\admincategory.php on line 50
And my function is:
<?php
class Admincategory extends Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$category = $this->model->getChildren(0);
$data = ['category' => $category];
$this->view('admin/category/index', $data);
}
function showchildren($idcategory)
{
$categoryInfo = $this->model->categoryInfo($idcategory);
$children = $this->model->getChildren($idcategory);
$parents = $this->model->getParents($idcategory);
$data = ['categoryInfo' => $categoryInfo, 'category' => $children, 'parents' => $parents];
$this->view('admin/category/index', $data);
}
function addcategory($categoryId = 0, $edit = '')
{
if (isset($_POST['title'])) {
$title = $_POST['title'];
$parent = $_POST['parent'];
$this->model->addCategory($title, $parent, $edit, $categoryId);
}
$category = $this->model->getCategory();
$categoryInfo = $this->model->categoryInfo($categoryId);
$data = ['category' => $category, 'parentId' => $categoryId, 'edit' => $edit, 'categoryInfo' => $categoryInfo];
$this->view('admin/category/addcategory', $data);
}
function deletecategory($parentId)
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
}
?>
app.php file
<?php
class App
{
public $controller = 'index';
public $method = 'index';
public $params = [];
function __construct()
{
if (isset($_GET['url'])){
$url = $_GET['url'];
$url = $this->parseUrl($url);
$this->controller = $url[0];
unset($url[0]);
if (isset($url[1])){
$this->method = $url[1];
unset($url[1]);
}
$this->params = array_values($url);
}
$controllerUrl = 'controllers/' . $this->controller . '.php';
if (file_exists($controllerUrl)) {
require($controllerUrl);
$object = new $this->controller;
$object->model($this->controller);
if (method_exists($object, $this->method)) {
call_user_func_array([$object, $this->method], $this->params);
}
}
}
function parseUrl($url)
{
$url = filter_var($url, FILTER_SANITIZE_URL);
$url=rtrim($url,'/');
$url = explode('/', $url);
return $url;
}
}
?>
and index.php
<?php
require('views/admin/layout.php');
$category = $data['category'];
$categoryInfo = [];
if (isset($data['categoryInfo'])) {
$categoryInfo = $data['categoryInfo'];
}
$parents = [];
if (isset($data['parents'])) {
$parents = $data['parents'];
$parents = array_reverse($parents);
}
?>
<style>
.w400 {
width: 600px;
}
</style>
<div class="left">
<p class="title">
مدیریت دسته ها
(
<?php foreach ($parents as $row) { ?>
<a href="admincategory/showchildren/<?= $row['id']; ?>">
<?= $row['title']; ?>
</a>
-
<?php } ?>
<a href="admincategory/<?php if (isset($categoryInfo['id'])) {
echo 'showchildren/' . $categoryInfo['id'];
} else {
echo 'index';
} ?>">
<?php
if (isset($categoryInfo['title'])) {
echo $categoryInfo['title'];
} else {
echo 'دسته های اصلی';
}
?>
</a>
)
</p>
<a class="btn_green_small" href="admincategory/addcategory/<?= #$categoryInfo['id']; ?>">
افزودن
</a>
<a class="btn_red_small" onclick="submitForm();">
حذف
</a>
<form action="admincategory/deletecategory/<?= #$categoryInfo['id']; ?>" method="post">
<table class="list" cellspacing="0">
<tr>
<td>
ردیف
</td>
<td>
عنوان دسته
</td>
<td>
مشاهده زیر دسته ها
</td>
<td>
ویرایش
</td>
<td>
انتخاب
</td>
</tr>
<?php
foreach ($category as $row) {
?>
<tr>
<td>
<?= $row['id']; ?>
</td>
<td class="w400">
<?= $row['title']; ?>
</td>
<td>
<a href="admincategory/showchildren/<?= $row['id']; ?>">
<img src="public/images/view_icon.png" class="view">
</a>
</td>
<td>
<a href="admincategory/addcategory/<?= $row['id']; ?>/edit">
<img src="public/images/edit_icon.ico" class="view">
</a>
</td>
<td>
<input type="checkbox" name="id[]" value="<?= $row['id']; ?>">
</td>
</tr>
<?php } ?>
</table>
</form>
</div>
</div>
============
Thank you for trying to help!
Sometimes it happen that AdminCategory::deletecategory($parentId) is called without a parameter but prototype do not have a default value for it and therefore exception is thrown. Since you get data from a post request and there is always a possibility that a category do not have a parent you can refactor your method to looks like:
function deletecategory($parentId = null)
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
if (null !== $parentId) {
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
// PUT MORE OF YOUR LOGIC HERE, I DO NOT KNOW WHAT SHOULD HAPPEN
}
If you are using typing hints more appropriate would be to make method looks like
function deletecategory(string $parentId = ''): void //void is for php7.1
{
$ids = $_POST['id'];
$this->model->deletecategory($ids);
if ('' !== $parentId) {
header('location:'.URL.'admincategory/showchildren/'.$parentId);
}
// AGAIN LOGIC HERE
}
If you REALLY expect that parentId MUST be passed then instead wrap method caller with try catch
if (method_exists($object, $this->method)) {
try {
call_user_func_array([$object, $this->method], $this->params);
} catch (\Exception $ex) {
// HANDLE EXCEPTION HERE
}
}
I have a error on my view which I am trying to work out why but not know how to fix.
A PHP Error was encountered
Severity: Warning
Message: in_array() expects parameter 2 to be array, boolean given
What would be the best method to fix this I think it has something to do with my post permission[access] on controller that's effecting view.
View
<div class="form-group">
<label class="col-sm-2 control-label">Access Permission</label>
<div class="col-sm-10">
<div class="well well-sm" style="height: 200px; overflow: auto;">
<?php foreach ($permissions as $permission) { ?>
<div class="checkbox">
<label>
<?php if (in_array($permission, $access)) { ?>
<input type="checkbox" name="permission[access][]" value="<?php echo $permission; ?>" checked="checked" />
<?php echo $permission; ?>
<?php } else { ?>
<input type="checkbox" name="permission[access][]" value="<?php echo $permission; ?>" />
<?php echo $permission; ?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<a onclick="$(this).parent().find(':checkbox').prop('checked', true);">Select All</a> / <a onclick="$(this).parent().find(':checkbox').prop('checked', false);">Unselect All</a></div>
</div>
Controller Function
public function getForm() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$id = $this->uri->segment(4);
if (isset($id) && $this->input->server('REQUEST_METHOD') != 'POST') {
$user_group_info = $this->model_user_group->getUserGroup($id);
}
$ignore = array(
'admin',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header'
);
$data['permissions'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
//$part = explode('/', dirname($file));
$permission = basename(strtolower($file), '.php');
if (!in_array($permission, $ignore)) {
$data['permissions'][] = $permission;
}
}
if (null !==($this->input->post('permission[access]'))) {
$data['access'] = $this->input->post('permission[access]');
} elseif ($user_group_info['permission']['access']) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
$this->load->view('template/user/users_group_form.tpl', $data);
}
I belive the problem lies in your controller, like you initially said. Try this:
In your controller, replace this:
if (null !== $this->input->post('permission[access]')) {
$data['access'] = $this->input->post('permission[access]');
} elseif ($user_group_info['permission']['access']) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
with this:
$permission_access = $this->input->post('permission');
if (isset($permission_access)) {
if (isset($permission_access['access'])) {
$data['access'] = $permission_access['access'];
} elseif ($user_group_info['permission']['access']) {
$data['access'] = $user_group_info['permission']['access'];
} else {
$data['access'] = array();
}
}