Codeigniter & Datamapper: Form Saving is behaving strange - php

I have a weird problem with Codeigniter and Datamapper,
I am making an CMS system and I am trying to edit an article from the Database using Datamapper. When I click to edit the article I get the message 'You have succesfully saved the article ' without clicking on the SAVE button, also all the data becomes empty and leaves 0. When I enter the data and click on SAVE it saves it but again when I try edit it again it goes back to 0 ... Can someone help out please
Here is my edit function in the controller
public function edit($id = NULL)
{
// Get articles by ID
$articles = new Article_model();
$article = $articles->where('id', $id)->get();
if ($id)
{
$id == NULL || $article;
count($article) || $error = 'Page not found ';
}
else
{
$article = $this->article_model->get_new();
}
$article->title = $this->input->post('title');
$article->text = $this->input->post('text');
if ($article->save())
{
echo 'You have succesfully saved the article';
}
else
{
echo 'Sorry something went terribly worng';
}
$data = array(
'admin_content' => 'admin/article/edit',
'article' => $article,
);
$this->parser->parse('admin/template_admin', $data);
}
and here is my view
<?php if ($this->tank_auth->is_logged_in()): ?>
<div class="container">
<div class="row">
<div class="col-md-9">
<h3><?php echo empty($article->id) ? 'Add an article' : 'Edit a Page ' . $article->title ;?></h3>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Publication Date</td>
<td><?php echo form_input('pubdate', set_value('pubdate', $article->pubdate), 'class="datepicker"'); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('text', set_value('text' , $article->text), 'class="tinymce"'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
</div>
</div>
<?php else: redirect('/auth/login'); ?>
<?php endif; ?>

that's not weird at all...every time that controller is loaded it's going to execute the save() method of the article class.
you should probably include some form validation and only save the article if the form was submitted and validation passes.

Related

Why does the paging of a dataTable not work when filling the data again with Ajax?

I have a jQuery dataTable that depending on the option you select in a previous Select shows you some data or others. By default it shows those of the first option and so far everything is correct.
The problem comes when I select the second option, that the dataTable seems to be unconfigured and shows me all the results in a row without respecting the Paginate, also if I try to sort by name or another field it will show me the first option again. The same is also true if I try to change the table page.
I don't know where the error is.
I attach some images as a sample:
First option (everything works perfect): image
On select second option: image , image2
If i try to click on tabs 1 to 7 or p.ex. order the column
Universitatautomatically shows this (results of the first selector but without respecting the design of the table) image
First option selector code:
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane fade in active no-info" id="tab1default">
<?php if($isAdmin){ ?>
<input type="hidden" id="niuProfessor" value="<?php echo $niu; ?>">
<div class="padding-bottom-20">
<select id="selectIfAdmin">
<option id="mineAdmin" value="mineAdmin">Les meves Universitats</option>
<option id="allAdmin" value="allAdmin">Totes les Universitats</option>
</select>
</div>
<!--<div id="showByGrau" class="padding-bottom-20" >
<select id="selectGrauAdmin">
<option value="-1">Tots els graus </option>
<?php foreach($degrees as $degree): ?>
<option value="<?php echo $degree->codiEstudis; ?>"><?php echo $degree->nomGrau; ?></option>
<?php endforeach; ?>
</select>
</div>-->
<?php } ?>
<div id="acordsTeacherAdmin" class="table-responsive">
<table class="table table-hover cell-border display compact" id="dev-table">
<thead>
<tr>
<th>Universitat</th>
<!-- <th>Grau</th>-->
<th>Places</th>
<th>Mesos</th>
<th>Període</th>
<!--<th>Assignatures</th>-->
<th><em class="fa fa-cog"></em></th>
</tr>
</thead>
<tbody id="taulaAcordsCoordinador">
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<!--<td><?php echo $ag->nomGrau; ?></td>-->
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
</div>
</div>
<div id="debug">
</div>
</div>
</div>
Second option code (TaulaAcordsCoordinador.php):
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
EventListener:
,$(document).on("change", "#selectIfAdmin", function(e){
e.preventDefault();
var data = {};
data.niu = $("#niuProfessor").val();
data.filtre = $(this).val();
filtrarAcordsAdmin(data);
})
Function with Ajax call:
function filtrarAcordsAdmin(data){
$.ajax({
type: "POST",
url: "perfil.php/" + "filtrarAcordsAdmin",
data: {"data":JSON.stringify(data)},
success: function(t, e, c) {
$("#taulaAcordsCoordinador").html(t);
/*if(data.filtre === "allAdmin"){$("#showByGrau").css('display','block');}
else{$("#showByGrau").css('display','none');}*/
},
error: function(t, e) {
}
})}
Perfi.php code:
case 'filtrarAcordsAdmin':
$actionName = "filtrarAcordsAdmin";
$data['data'] = $_POST['data'];
array_push($parameters,$data);
break;
filtrarAcordsAdmin controller:
public function filtrarAcordsAdmin($parameters){
$data = json_decode($parameters[0]['data']);
require_once 'models/TeachersModel.php';
require_once 'models/ConvenisModel.php';
$teachersModel = new TeachersModel();
$convenisModel = new ConvenisModel();
if($data->filtre == 'mineAdmin'){
$agree = $teachersModel->getAgreementsTeacher($data->niu);
}elseif ($data->filtre == 'allAdmin'){
$agree = $convenisModel->getConvenis();
}
$teachersModel->disconnect();
$convenisModel->disconnect();
$route = $this->view->show("TaulaAcordsCoordinador.php");
include($route);
}
Both functions getConvenis() and getAgreementsTeacher() are functions of a model that returns de result of a query into the BD like that:
public function getConvenis(){
try {
$consulta = $this->db->prepare('SELECT uni.nomUniversitat, uni.idUniversitat, es.nomGrau,co.codiConveni,co.codiCentreEstudis,ce.plaçes,ce.mesos,ce.període
FROM centreestudis ce, universitat_estudisuab un,universitats uni,estudisuab es,conveni co
WHERE ce.codiUniEstudis = un.codiUniEstudis
AND uni.idUniversitat = un.idUniversitat
AND un.codiEstudis = es.codiEstudis
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY uni.nomUniversitat');
$consulta->execute();
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
} catch (Exception $e) {
}
return $obj;
}
public function getAgreementsTeacher($niu){
try {
$consulta = $this->db->prepare('SELECT ce.plaçes, ce.mesos, ce.període , un.nomUniversitat ,un.idUniversitat,co.codiConveni, eu.nomGrau
FROM professorscentre pr, centreestudis ce, universitat_estudisuab ue, estudisuab eu, universitats un, conveni co
WHERE pr.niuProfessor = ?
AND ce.codiCentreEstudis = pr.codiCentreEstudis
AND ue.codiEstudis = eu.codiEstudis
AND ce.codiUniEstudis = ue.codiUniEstudis
AND un.idUniversitat = ue.idUniversitat
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY un.nomUniversitat');
$consulta->execute(array($niu));
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
return $obj;
} catch (Exception $e) {
}
}

Codeigniter send GET parameter with site_url?

I have this part of code in my view file:
<?php foreach ($posts as $post) { ?>
<tr>
<td><?php echo $post['id']; ?></td>
<td><?php echo $post['title']; ?></td>
<td><?php echo $post['content']; ?></td>
<td>
<div class="btn-group">
Edit
Delete
</div>
</td>
</tr>
<?php } ?>
Well .. how to send GET parameter with site_url function, this is my anchor part:
a href="<?php echo site_url('admin/blog/show'); ?>" class="btn btn-success">Edit</a>
where to send $post['id'] ?
I see some question in SO, but answers was with hardcode...
here we have a example
echo anchor('news/local/'. $post['id'], 'any text', array('title' => 'The best news!'));
In your controller you will get something like.
echo $this->uri->segment('3');
Also load url helper/library as well.
Should be like this :
Edit
The given code should be like this :
<?php foreach ($posts as $post) { ?>
<tr>
<td><?=$post['id']; ?></td>
<td><?=$post['title']; ?></td>
<td><?=$post['content']; ?></td>
<td>
<div class="btn-group">
Edit
Delete
</div>
</td>
</tr>
<?php } ?>
In your show method access post id like this :
public function show($post_id)
{
echo $post_id;
}
For more : https://www.codeigniter.com/user_guide/helpers/url_helper.html

Echo user info on another users profile page

I'm trying to make a function in the CodeIgniter framework so users can click on product detail page, and see which user uploaded that certain product and they must be able to click on the product owner to go to his profile page.
Now, I am already able to echo owner information of the product owner on the details page. But the link to the owner profile page is not working some reason and the name isn't echoed anymore since I tried to make it a link.
This is my product details page (details.php) foreach loop function where I'm trying to echo the username of the owner of a product and link it to their profile page:
<?php include_once ('templates/header.php'); ?>
<div class="container">
<h3>Email van de eigenaar:</h4>
<?php
foreach ($userdetail_list as $row) {
?>
<tr>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } ?>
</div>
<div class="container">
<div class="row">
<div class="col-md-4" style="margin-top:24px;">
<img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" class="img-responsive">
</div>
<div class="col-md-5">
<h1> <div class="product_naam"> <?php echo $product['product_naam']; ?> </div> </h1>
<h3>Over dit cadeau</h3>
<div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
</div>
<div class="col-md-3">
<button type="button" class="btn btn-default">Cadeau aanvragen</button>
<div class="aangeboden_door"> Aangeboden door: <?php
foreach ($userdetail_list as $row) { ?>
<tr>
<td><?= $row['username']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="container">
<footer>
<p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
When I load this view file I do see the echoeod email but not the username? And there is also no link to the users profile page..
Here is my controller file (User.php):
<?php
class User extends CI_Controller {
public function index() {
$this->load->view('profile', $data);
}
public function __construct() {
parent::__construct();
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
}
public function userdetails($user_id) {
//load the User_model
$this->load->model('User_model');
//call function getdata in de Product_model
$data['userdata_list'] = $this->User_model->getdata();
//get product details
$data['user'] = $this->User_model->get_user_info($user_id);
//laad view
$data['main_content'] = 'profiel_user';
$this->load->view('profiel_user', $data);
}
public function profile() {
$this->load->model('User_model');
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
$this->load->view('profile');
}
}
?>
And here is my model (User_model.php) :
<?php
public function getdata()
{
$this->db->where('user_id', $id);
$this->db->from('users');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
}
public function getUserInfo($user_id) {
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if ($this->db->affected_rows() > 0) {
$row = $q->row();
return $row;
} else {
error_log('no user found getUserInfo(' . $user_id . ')');
return false;
}
}
?>
Database information:
I have 2 tables:
users:
user_id
voornaam
achternaam
email
password
(products:
product_id
product_name
product_description)
I hope someone can help me,
Thanks!
You are concatenating user name in anchor tag herf separate it and write between <a> and </a>
change your code as below:
<tr>
<td><?=$row['username']; ?></td>
<td><?php echo $row['email'];?></td>
</tr>
You can try this solution for your problem.
Please change your view file.
details.php
<tr>
<td><?= $row['username']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
and please changes your controller function:
User.php
<?php
public function profiel_user($user_id) {
$this->load->model('User_model');
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error", "Please login first to view this page!! ");
redirect("auth/login");
}
$data['user_id'] = $user_id; // you can used user id for getting data
$this->load->view('profile');
}
?>
Thanks

Ajax Pagination backward move in cakephp 3

I am doing ajax pagination in cakephp 3.2
I have done code for forward move of pagination, by getting the last id .
If i want to go backward ,the pagination will not work ,i know .
How can i do it in a proper way so that it will work for both direction as well as direct click on any pagination index.
Below i have attached some of my codes ,which is working properly only for forward move of pagination.
I know the code won't work for backward move.
How can i do it?
///////////////////////////////////PAGINATION STARTS HERE/////////////////////////////////////////////////
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1; //if there's no page number, set it to 1
}
$item_per_page=5;
$get_total_rows = $this->Orders->find('all')->where($condition)->count(); //hold total records in variable
$total_pages = ceil($get_total_rows/$item_per_page);
$page_position = (($page_number-1) * $item_per_page);
if($page_number>1)
{
$condition[] = ['Orders.id >' => $_POST["lastId"]];
}//this one fetch all list greater than last id
$Lists = $this->Orders->find('all')->where($condition)->order(['Orders.id' => 'ASC'])->limit($item_per_page)->toArray();
Thank you
Your Controller Action code should be
$this->paginate = [
'order'=>[
'field_name'=>'desc'
]
];
$condition = [];
$query = $this->YourModel->find()->where($conditions);
$this->set('records', $this->paginate($query));
In view your code should be for listing part only, I dont know whta is your HTML structure but you can follow this, and dont forget about id=pagination_list_container in parent of your table and pagination link code.
<div class="panel-body" id="pagination_list_container">
<div class="inner-spacer">
<table class="table table-striped table-hover margin-0px">
<thead>
<tr>
<th><?php echo $this->Paginator->sort('field_1', 'Column 1') ?></th>
<th><?php echo $this->Paginator->sort('field_2', 'Column_2') ?></th>
<th><?php echo $this->Paginator->sort('field_3', 'Column_3') ?></th>
</tr>
</thead>
<tbody>
<?php
if (empty($records->toArray())) {
?>
<tr><td colspan="100%" class="text-danger text-center">No record found</td></tr>
<?php
} else {
foreach ($records as $record):
?>
<tr>
<td><?php echo $record->field_1 ?></td>
<td><?php echo $record->field_2; ?></td>
<td><?php echo $record->field_3; ?></td>
</tr>
<?php endforeach; ?>
<?php } ?>
</tbody>
</table>
</div>
<div class="row">
<div class="col-md-6">
<ul class="pagination">
<?php
$this->Paginator->templates([
'current' => '<li class="active"><a>{{text}}</a></li>',
'number' => '<li>{{text}}</li>'
]);
echo $this->Paginator->prev('«');
echo $this->Paginator->numbers();
echo $this->Paginator->next('»');
?>
</ul>
</div>
<div class="col-md-6 text-right">
<div class="mt30">
<?php
echo $this->Paginator->counter(
'Page {{page}} of {{pages}}, showing {{start}} to {{end}} of {{count}}'
);
?>
</div>
</div>
</div>
</div>
Make AJAX behaviour in your view
You have to Apply Some Javascript event for ajax behaviour into #pagination_list_container
$(document).ready(function(){
$("document").on('click','#pagination_list_container .pagination li a, #pagination_list_container table th > a', function(e){
e.preventDefault();
var link= $(this).attr('href');
if(link!="")
{
$("#pagination_list_container").load(link+ "#pagination_list_container", function(){
console.log("data loaded");
})
}
return false;
});
});

Custom table names in CakePHP

I am building a portfolio website using CakePHP and have named my model 'Portfolio' and my controller 'PortfolioController' however cake decides to look for a table called portfolios instead of just portfolio! How can I fix this as I don't want to call my table portfolios!
Also when dealing with the foreach loop in the views where it has statements like
<?php foreach ($posts as $post): ?> how would I deal with the plural issue with my portfolio?
Thanks
EDIT Here is the index.ctp file where I have the plural issue:
<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Action</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Portfolio']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Portfolio']['title'], array('action' => 'view', $post['Portfolio']['id']));?>
</td>
<td>
<?php echo $this->Html->link(
'Delete',
array('action' => 'delete', $post['Portfolio']['id']),
null,
'Are you sure?'
)?>
<?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Portfolio']['id']));?>
</td>
<td><?php echo $post['Portfolio']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
EDIT Here is the controller:
<?php
class PortfolioController extends AppController
{
var $helpers = array ('Html','Form');
var $name = 'Portfolio';
function index()
{
$this->set('portfolio', $this->Portfolio->find('all'));
}
function view($id = null)
{
$this->Portfolio->id = $id;
$this->set('portfolio', $this->Portfolio->read());
}
function add()
{
if (!empty($this->data))
{
if ($this->Portfolio->save($this->data))
{
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id)
{
if ($this->Portfolio->delete($id))
{
$this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'index'));
}
}
function edit($id = null)
{
$this->Portfolio->id = $id;
if (empty($this->data))
{
$this->data = $this->Portfolio->read();
}
else
{
if ($this->Portfolio->save($this->data))
{
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
Class Portfolio extends App_Model{
public $useTable = 'portfolio';
}
in you model you can set the $useTable variable to be whatever you need.
in views you pass variable values from controllers with set method
$this->set('portfolio',$array_of_data);
so the first parameter can be anything you like.
in the index action.
$this->set('portfolio', $this->Portfolio->find('all'));
see the code here? that's what I meant.
you are setting $portfolio variable for your view. so you must change all your $posts variables into $portfolio variables.
<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Action</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($portfolio as $portfolio_item): ?>
<tr>
<td><?php echo $portfolio_item['Portfolio']['id']; ?></td>
<td>
<?php echo $this->Html->link($portfolio_item['Portfolio']['title'], array('action' => 'view', $portfolio_item['Portfolio']['id']));?>
</td>
<td>
<?php echo $this->Html->link(
'Delete',
array('action' => 'delete', $portfolio_item['Portfolio']['id']),
null,
'Are you sure?'
)?>
<?php echo $this->Html->link('Edit', array('action' => 'edit', $portfolio_item['Portfolio']['id']));?>
</td>
<td><?php echo $portfolio_item['Portfolio']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
or change portfolio in set method to posts like this.
$this->set('posts', $this->Portfolio->find('all'));

Categories