I'm trying to change the URL parameter from the row ID to the NAME of the article. here is my code
Controllers
public function view($id=0)
{
if( !isset($id) || !is_numeric($id) ) {
redirect(base_url());
}
$tot = $this->Model_service->service_check($id);
if(!$tot) {
redirect(base_url());
}
and the view is
<?php
foreach ($services as $row) {
?>
<div class="col-lg-4 col-md-6">
<div class="services-item effect-item">
<a href="<?php echo base_url(); ?>service/<?php echo $row['name']; ?>" class="image-effect">
<div class="services-photo" style="background-image: url(<?php echo base_url(); ?>public/uploads/<?php echo $row['photo']; ?>)"></div>
</a>
<div class="services-text">
<h3><?php echo $row['name']; ?></h3>
<p>
<?php echo nl2br($row['short_description']); ?>
</p>
<div class="button-bn">
<?php echo READ_MORE; ?> <i class="fa fa-chevron-circle-right"></i>
please help me with the most simplified answer thank you
Yo need to change your article view function in controller. Lookup article name instead of id. But name might contains spaces which is not URL friendly so using concept of slug will solve this.
public function view($slug='')
{
if($slug == '') {
redirect(base_url());
}
$tot = $this->Model_service->find_service_by_slug($slug);
if(!$tot) {
redirect(base_url());
}
Reference link for concept of slug is https://codeigniter.com/user_guide/tutorial/news_section.html
Related
Actually I am working on front-end, but I cannot reach the backend developer and I need to fix a bug.
The problem is exactly this, if there is no image in a content, we get an error like this:
A PHP Error was encountered
A
Severity: Notice
Message: Undefined property: stdClass:$Pictures
Filename:agent/hotel_detail.php
Line Number: 17
Backtrace:
File:/home/tungatour/public_html/application/views/agent/hotel_detail.php
Line: 17
Function: _error_handler
File:/home/tungatour/public_html/application/controllers/Agent.php
Line: 490
Function: view
File:/home/tungatour/public_htm/index.php
I just want to show demo image instead if there is no image. But i dont have any idea how can i do this ?
so i have controller codes about picture this this.
public function post($ID)
{
$viewData["title"] = "Post Details";
$data = $this->db->where("ID", $ID)->get("post")->row();
$data->Meta = json_decode($data->Meta);
$picture = $this->db->where("ID", $data->Meta->Thumbnail)->get("picture")->row();
$viewData["data"] = $data;
$viewData["picture"] = $picture;
$this->load->view('partials/agent/head', $viewData);
$this->load->view('agent/post', $viewData);
$this->load->view('partials/agent/foot', $viewData);
}
also i have this lines` <?php $first = true;
for ($i = 0; $i < $this->db->where_in("ID", $data->Meta->Pictures)->count_all_results("picture"); $i++) { ?>
<li data-target="#carousel-example-generic" data-slide-to="<?= $i ?>" class="<?= $first ? "active" : "" ?>"></li>
<?php $first = false;
} ?>
</ol>
<div class="carousel-inner" role="listbox">
<?php $first = true;
foreach ($this->db->where_in("ID", $data->Meta->Pictures)->get("picture")->result() as $picture) { ?>
<div class="carousel-item <?= $first ? "active" : "" ?>">
<img class="img-fluid" src="<?= $picture->URL ?>" style="height: 420px;width: 100%;object-fit: cover;" />
</div>
<?php $first = false;
} ?>
</div>`
Change this line
<img class="img-fluid" src="<?= $picture->URL ?>" style="height: 420px;width: 100%;object-fit: cover;" />
Update with
<?php if($picture->URL) { ?>
<img class="img-fluid" src="<?= $picture->URL ?>" style="height: 420px;width: 100%;object-fit: cover;" />
<?php } ?>
If the image has a URL, it will display the image. Otherwise it will be empty.
I have edited Comment module from a tutorial to review module.
In this module i using CStarRating widget. When view, submit, delete rate post it OK. but when i click edit/update, edit old post and click update to edit rate post then star don't show, instead this radio group ???
Here is code:
CommentList.php
<?php
/** #var CArrayDataProvider $comments */
$comments = $model->getCommentDataProvider();
$comments->setPagination(false);
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$comments,
'itemView'=>'comment.views.comment._view'
));
$this->renderPartial('comment.views.comment._form', array(
'comment'=>$model->commentInstance
));
_view.php
<?php
?>
<nav id = "atext" >
<div>
<span class="ext-comment-head">
wrote on
<span class="ext-comment-date">
<?php echo Yii::app()->format->formatDateTime(
is_numeric($data->createDate) ? $data->createDate : strtotime($data->createDate)
);
?>
</span>
</span>
<span class="ext-comment-options">
<?php if (!Yii::app()->user->isGuest && (Yii::app()->user->id == $data->userId)) {
echo CHtml::ajaxLink('delete', array('/comment/comment/delete', 'id'=>$data->id), array(
'success'=>'function(){ $("#ext-comment-'.$data->id.'").remove(); }',
'type'=>'POST',
), array(
'id'=>'delete-comment-'.$data->id,
'confirm'=>'Are you sure you want to delete this item?',
));
echo " | ";
echo CHtml::ajaxLink('edit', array('/comment/comment/update', 'id'=>$data->id), array(
'replace'=>'#ext-comment-'.$data->id,
'type'=>'GET',
), array(
'id'=>'ext-comment-edit-'.$data->id,
));
} ?>
</span>
<p id = "apa">
<br>
</p>
<table id = "atable">
<td id = "test123">
<?php
$model=new Comment;
$a=$data->id;
$colArr=$model->attributes;
for ($i = 0; $i < count($colArr); $i++) {
$key=key($colArr);
$val=$colArr[$key];
next($colArr);
if (($key<> 'average') and($key<>'id') and ($key<>'message')
and ($key<>'userId') and ($key<>'createDate') ) {
$a=$a+100;
echo $data->getAttributeLabel($key).' ('.$data->$key.')';
$this->widget('CStarRating',array(
'name'=>'Comment['.$a.']',
'value'=>$data->$key,
'minRating'=>1, //minimal value
'maxRating'=>5,//max value
'starCount'=>5, //number of stars
'readOnly'=>true,
));
}
echo "<br>";
}
?>
</td>
<td id = "average-teacher">
<p>
<?php echo nl2br(CHtml::encode($data->message)); ?>
</p>
</td>
</table>
<br style="clear: both;"/>
</div>
</nav>
</div>
_form.php
<br>
<br>
<?php if (Yii::app()->user->isGuest) {
?><div class="ext-comment-not-loggedin">
Sorry, you have to login to leave a comment.
</div><?php } else { ?>
<div id="ext-comment-form-<?php echo $comment->isNewRecord ? 'new' : 'edit-'.$comment->id; ?>" class="form" >
<nav id = "comment-a">
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'ext-comment-form',
'action'=>array('/comment/comment/create'),
'enableAjaxValidation'=>false
)); ?>
<?php /** #var CActiveForm $form */
echo $form->errorSummary($comment); ?>
<div class="row">
<?php echo $form->labelEx($comment,'message'); ?>
<?php echo $form->textArea($comment,'message',array('rows'=>3, 'cols'=>76)); ?>
<?php echo $form->error($comment,'message'); ?>
</div>
<?php
$model=new Comment;
$colArr=$model->attributes;
for ($i = 0; $i < count($colArr); $i++) {
$key=key($colArr);
if (($key<> 'average') and ($key<>'id') and ($key<>'message') and ($key<>'userId')
and ($key<>'createDate') ){
$this->widget('CStarRating',array(
'name'=>'Comment['.$key.']',
'value'=>$model->$key,
'minRating'=>1, //minimal value
'maxRating'=>5,//max value
'starCount'=>5, //number of stars
));
echo " ".$model->getAttributeLabel($key)."<br>";
echo "<br>";}
next($colArr);
}
?>
<div class="row buttons">
<?php if ($comment->isNewRecord) {
echo "<br>";
echo $form->hiddenField($comment, 'type');
echo $form->hiddenField($comment, 'key');
echo CHtml::ajaxSubmitButton('Submit',
array('/comment/comment/create'),
array(
'replace'=>'#ext-comment-form-new',
'error'=>"function(){
$('#Comment_message').css('border-color', 'red');
$('#Comment_message').css('background-color', '#fcc');
}"
),
array('id'=>'ext-comment-submit' . (isset($ajaxId) ? $ajaxId : ''))
);
} else {
echo CHtml::ajaxSubmitButton('Update',
array('/comment/comment/update', 'id'=>$comment->id),
array(
'replace'=>'#ext-comment-form-edit-'.$comment->id,
'error'=>"function(){
$('#Comment_message').css('border-color', 'red');
$('#Comment_message').css('background-color', '#fcc');
}"
),
array('id'=>'ext-comment-submit' . (isset($ajaxId) ? $ajaxId : ''))
);
}
echo "<br>";
?>
</div>
<?php $this->endWidget() ?>
</nav>
</div><!-- form -->
<?php } ?>
Hope someone can help me :( And sorry about my english :(
I have a page written in codeigniter framework.
Now I want to add a button to page (eg 'show more') that will get data with 'ajax.php' from the database and display them on the site, but I do not want it separately connect to the database and then get the results, just want to be able to collect data (in ajax.php) as well as in codeigniter controllers (using models)...
Hope you understand me :)
Here you go just add view more button and call this js and ajax function..This is code i have used please see it and use it as per your requirment
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$("ol#updates").addClass('tiny-loader');
this_tag.html('Loading.....');
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").removeClass('tiny-loader');
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old view-more button
});
}
else
{
this_tag.fadeOut('slow');// no results
}
return false;
});
code in ajax file
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_more extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('general_model');
$this->limit =REVIEW_DETAIL;
}
public function index($offset = 0)
{
$lastmsg=$this->input->post('lastmsg');
$rest_id=$this->input->post('restid');
$value=('reviews.*,usermaster.Name as User');
$joins = array
(
array
(
'table' => 'tk_usermaster',
'condition' => 'usermaster.Id = reviews.UserId',
'jointype' => 'leftouter'
),
);
$this->results = $this->general_model->get_joinlist('reviews',$value,$joins,array('reviews.Status'=>'Enable','reviews.RestaurantId'=>$rest_id,'reviews.Id <'=>$lastmsg),'reviews.Id','desc',$this->limit,$offset);
$data['list_review']= $this->results['results'];
?>
<?php foreach ($data['list_review'] as $row): ?>
<div class="user_reviews_data" >
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10 "><div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div></span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id = $row->Id;
endforeach; ?>
</div>
<div id="more<?php echo #$msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
<?php
}
}
I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.
The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink
I am struggling with nested tab markup generated via Codeigniter model calls and would welcome any insightful comments. The difficulty is that the markup generated has unwanted repetitions of blocks of project data. The use of multiple views which are not straightforwardly inter-connected is probably where the problems lie.
Here's the controller:
function projects() {
$this->load->model('msm_projects');
$data['cats']=$this->msm_projects->catid()->result_array();
$this->load->view('vup_projects', $data);
foreach ( $data['cats'] as $item )
{
$data2['projects']=$this->msm_projects->catproj($item['catid'])->result_array();
$this->load->view('vup_projects2', $data2);
}
}
The model:
function catid() {
return $this->db->query("SELECT DISTINCT catid, cat FROM category INNER JOIN projects ON catid = projcat WHERE projpub=1 ORDER BY catid ASC");
}
function catproj($catid) {
return $this->db->query("SELECT catid, cat, projcat, projid, projtit FROM projects INNER JOIN category ON projcat = catid WHERE projcat = $catid AND projpub=1 ORDER BY catid ASC");
}
Here are the views which are in two parts. I suspect this is where it's all going wrong. There's an imperfect join between the two views which I am having a hard time thinking about.
view 1 called 'vup_projects'
<div id="wrapper">
<div class="yui3-g">
<div class="yui3-u-1"><div id="topbloc"><img src="http://localhost/getop/base-images/topbloc.gif" width="800" height="50" align="middle"></div></div>
<div class="yui3-u-1">
<div id="navbloc">
<div id="linx">
<ul >
<li id="about"><?php echo anchor('cu_tya/about', 'about'); ?></li>
<li id="ourwork"><?php echo anchor('cu_projects/projects', 'projects'); ?></li>
<li id="contact"><?php echo anchor('cu_tya/contact', 'contact'); ?></li>
<li id="member"><?php echo anchor('cu_sites/pager', 'your page'); ?></li>
</ul>
</div>
</div>
</div>
<div class="yui3-u-1">
<div id="container">
<ul>
<?php
foreach ( $cats as $item ) // top tabs
{
echo '<li><a href=#fragment-'.$item['catid'].'><span>'.$item['cat'].'</span></a></li>';
}
?>
</ul>
And the second view vup_projects2
<?php foreach ( $cats as $item ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $item['catid'];?>">
<ul>
<?php foreach ( $projects as $project )
{ ?>
<li>
<span><?php echo $project['projtit'];?></span></li>
<?php } ?>
</ul>
<?php foreach ( $projects as $project )
{ ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div>
<?php } ?>
</div> <!-- container -->
</div> <!-- YUI-UNIT-1-->
</div> <!-- YUI-GRID -->
</div> <!-- wrapper -->
foreach ( $data['cats'] as $item )
{
$data2['projects']=$this->msm_projects->catproj($item['catid'])->result_array();
$this->load->view('vup_projects2', $data2);
}
is your problem, you're looping the views for every item in $data['cats']... you're also doing a query for every $item. You should do one query and then loop through the results accordingly. But to fix your problem, try this:
foreach ( $data['cats'] as $item )
{
$data2['projects'][$item['catid']] = $this->msm_projects->catproj($item['catid'])
->result_array();
}
$this->load->view('vup_projects2', $data2);
then change your second view to
<?php foreach ( $cats as $item ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $item['catid'];?>">
<ul>
<?php foreach ( $projects[$item['catid']] as $project )
{ ?>
<li>
<span><?php echo $project['projtit'];?></span></li>
<?php } ?>
</ul>
<?php foreach ( $projects[$item['cat_id']] as $project )
{ ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div> <!-- container -->
</div> <!-- YUI-UNIT-1-->
</div> <!-- YUI-GRID -->
</div> <!-- wrapper -->
So I took a closer look at what your trying to accomplish and I think I consolidated it into a single query and a single view. Maybe this will help
Controller:
class Projects extends CI_Controller {
function __construct(){
parent::__construct();
}
function projects() {
$cats = array(); // Unique cateogires
$projects = array(); // Projects that will go underneath
$this->load->model('msm_projects');
$query = $this->msm_projects->get_all();
// Make sure there are results
if ($query !== FALSE)
{
// Loop through once to find distinct categories for tabs
foreach ($query as $k => $v)
{
if ( ! array_key_exists($v['catid'], $tabs))
{
$tabs[$v['catid']] = $v['cat'];
}
}
// Loop through all of the results and group the items
// into arrays by their categories
foreach ($query as $k => $v)
{
$projects[$v['catid']][] = $v;
}
$data = array(
'cats' => $cats,
'projects' => $projects
);
$this->load->view('main', $data);
}
else
{
echo 'No results';
}
}
}
Model:
class Msm_projects extends CI_Model {
/* Returns everything you need */
function get_all()
{
$q = $this->db->select('c.catid, c.cat, p.projcat, p.projid, p.projtit')
->join('projects as p', 'c.catid = p.projcat', 'INNER')
->where('projpub = 1')
->order_by('c.catid')
->get('category as c');
if ($q->num_rows > 0)
{
return $q->result_array();
}
else
{
return FALSE;
}
}
}
View:
<div id="wrapper">
<div class="yui3-g">
<div class="yui3-u-1">
<div id="topbloc">
<img src="<?=base_url() /* Good not to hardcode url's if you can avoid it */;?>getop/base-images/topbloc.gif" width="800" height="50" align="middle" />
</div>
</div>
<div class="yui3-u-1">
<div id="navbloc">
<div id="linx">
<ul >
<li id="about"><?php echo anchor('cu_tya/about', 'about'); ?></li>
<li id="ourwork"><?php echo anchor('cu_projects/projects', 'projects'); ?></li>
<li id="contact"><?php echo anchor('cu_tya/contact', 'contact'); ?></li>
<li id="member"><?php echo anchor('cu_sites/pager', 'your page'); ?></li>
</ul>
</div>
</div>
</div>
<div class="yui3-u-1">
<div id="container">
<ul>
<?php foreach($cats as $id => $cat){ ?>
<li><span><?=$cat['cat'];?></span></li>
<?php } ?>
</ul>
<?php foreach ($cats as $id => $cat ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $id;?>">
<ul>
<?php foreach($projects[$id] as $project){ ?>
<li>
<span><?php echo $project['projtit'];?></span>
</li>
<?php } ?>
</ul>
<?php foreach ($projects[$id] as $project) { ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div>
<?php } ?>
There are a lot of tricks to learn about optimizing the MVC process in CI, a lot of which I wish I learned earlier. Hopefully this helps some, let me know if you have questions. As for the pagination, try doing something similar to what i did in the foreach loop to get the main categories, and then subsequently pulling the pages out of the result array which are == to the category you're looking for.