Codeigniter - return an anchor() from function - php

probably a newb question here, but how do I return a CI anchor() call from within a function. I want to "hide" a button if a variable is set to a certain value.
CI's URL helper documentation: https://www.codeigniter.com/user_guide/general/helpers.html
A pseudo example that won't work (can't return the URL helper anchor('',''):
$prevAvailCompID = 0;
function hideButton($prevCompID)
{
if($prevCompID == 0)
{
return anchor('/getcomps/getSpecificComp/'.$prevCompID , 'PREV COMP');
//I've also tried return echo anchor(...)
}
}
further down on the page:
<div id="prevBtnContainer"><? hideButton($prevAvailCompID); ?></div>

You don't need to return the anchor() function. You can just use as this
UPDATED CODE
public function test(){
?>
<h1>test H1</h1>
<div id="prevBtnContainer"><?php $this->hideButton(0); ?></div>
<div id="1prevBtnContainer"><?php $this->hideButton(1); ?></div>
<?php
}
private function hideButton($prevCompID)
{
if($prevCompID == 0)
{
echo anchor('/getcomps/getSpecificComp/'.$prevCompID , 'PREV COMP');
}
}
I've tested this in my CodeIgniter and its working.

Related

Fetch a variable defined in a different function inside a shortcode function

I'm trying to fetch a variable which is defined in a different function inside the same file into a different shortcode function, but it's not reflecting it, can anybody please let me know what I'm doing wrong
if ($hits[0]<= $varlinkhits)
{
$buttonlink="$varlinkone";
}
else
{
$buttonlink="$varlinktwo";
}
?>
<?php
//creating short code
?>
<button onclick="onclickRedirect()">redirect</button>
<script>
function onclickRedirect(){
window.location.href = "<?php echo $buttonlink ?>";
}
</script>
<?php
}
session_start();
function link_button_function() {
global $buttonlink;
$_SESSION["sessionlink"] = $buttonlink;
return 'Join Whatsapp Group';
}
add_shortcode('button_link', 'link_button_function');

Flash messages with sessions in PHP

I work on a project in PHP which does not use any kind of a framework for PHP. I come from Yii background and I've used:
Yii::app()->user->setFlash('flash_name', 'Flash value');
And checked it with:
Yii::app()->user->hasFlash('flash_name');
To check if it is present and if it exists, and to get the value of it I used:
Yii::app()->user->getFlash('flash_name', 'Default Flash value');
For now, I wrote these functions to set, check and get flash:
function set_flash($flash_name, $value) {
$_SESSION['flashes'][$flash_name] = $value;
}
function has_flash($flash_name) {
return isset($_SESSION['flashes'][$flash_name]) ? true : false;
}
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
return $_SESSION['flashes'][$flash_name];
}
return $default_value;
}
However, when I use it in my post.php like this:
set_flash('success', true);
And check it in my index.php like this:
<div class="container">
<?php if(has_flash('success') && (get_flash('success') === true)): ?>
<div class="alert alert-success">
<h4>Success!</h4>
<hr />
<p>You have successfully posted new content on your website. Now you can edit or delete this post.</p>
</div>
<?php endif; ?>
</div>
whenever I refresh the page, the message would still appear there.
How can I remove the flash after it's been used or invoked?
Add a new line to get_flash:
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
$retVal = $_SESSION['flashes'][$flash_name];
// don't unset before you get the vaue
unset($_SESSION['flashes'][$flash_name]);
return $retVal;
}
return $default_value;
}

HTML code in OOP PHP file

I want to get some advice of using PHP OOP.
For example I'm createing some PHP/MySQL code using OOP and I need to output the code, how to do it?
I might have been bit confusing, I will show you all the code and you tell me if I do it right:
index.php
<?php
require_once CLASSES."Pages.Class.php";
$obj = new Pages;
if (isset($_GET['page'])) {
$obj->setPage($_GET['page']);
echo $obj->getPage();
} else {
echo $obj->getFrontPage();
}
?>
Pages.Class.php - one function from it
public function getDatabasePage() {
global $conn;
$sql = "SELECT * FROM pages WHERE page_seo_title = '$this->pageId' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="well">
<div class="page-head">
<?php echo $row["page_title"]; ?>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="well">
<div class="page-content">
<?php echo $row["page_content"]; ?>
</div>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
}
So basiclly the question is: Where do I need to put HTML code?
In the index.php file or in the pages.class.php file?
How to do this right? Maybe I can get some links with documentation about this from you :) ..
Thanks.
btw - code is an example, not fully done. Just as example - I know it's not right as it is :D
In your Pages class, create a separate method that outputs HTML and does only that; the DB-related logic should be in another method or (preferably) in a totally separate class.
class Pages {
public function __construct(){
//Object initialization logic comes here
}
public function getOutputHTML($resultOfQuery = ''){
return "<div> Your html </div>";
}
}
Other class file only for DB access , just pass parameter and get result as Database result.
class DB {
public function insertMethod($table,$fields,$where){
//Your logic
}
public function updateMethod($table,$fields,$where){
//Your logic
}
public function deleteMethod($table,$fields,$where){
//Your logic
}
public function selectMethod($table,$fields,$where){
//Your logic
}
}
Instantiate DB class like $dbObj = new DB();
Then you can access DB methods like $resultQuery = $dbObj.selectMethod('users');
So you can pass the $resultQuery result to other method like : $objPages = new Pages();$objPages.getoutputHTML($resultOfQuery); . It separates the Database and HTML logic/functionality.
I recommand you to use OOP with MVC so there will be templating system like Smarty,Blade etc.

multiple zend pagination controls via ajax and jquery

Can someone help me achieve multiple zend pagination in a view using ajax. I have managed to achieve single pagination no problem, but now i want to perform more than 1.
this is my setup:-
added to the bootstrap:-
public function _initPaginator(){
Zend_Paginator::setDefaultScrollingStyle('Sliding');
Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination_control.phtml');
}
'pagination_control.phtml' has been taken from the zend framework manual.
added to the controller:-
public function init()
{
parent::init();
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('view', 'html')
->initContext();
}
added this to the controller action:-
public function viewAction()
{
$query = $this->_em->createQueryBuilder()
->select('t')
->from('Ajfit\Entity\Ticket', 't')
->where('t.engineerFk = :engineer')
->orderBy('t.dt', 'desc')
->setParameter('engineer', $engineer)
->getQuery();
$paginator = new Paginator($query);
$adapter->getIterator();
$zend_paginator = new \Zend_Paginator($adapter);
$zend_paginator->setItemCountPerPage(3)
->setCurrentPageNumber($this->_getParam('page'));
$this->view->ticketPaginator = $zend_paginator;
}
added this to the view:-
<div>
<div id="ticket-history">
<?php
echo $this->render('profile/view.ajax.phtml');
?>
</div>
</div>
<script>
$(document).ready(function() {
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#ticket-history').load(link.attr('href'), { format: 'html' });
return false;
});
});
</script>
my 'profile/view.ajax.phtml' script contains:-
<?php
echo '<table border="0" width="100%" cellspacing="3" cellpadding="3"><tr>';
foreach($this->ticketPaginator as $ticket){
echo '<td>' . $ticket->getSubject() . '</td>';
}
echo '</tr></table>';
?>
<?php
echo $this->paginationControl($this->ticketPaginator);
?>
This all works fine, however, how would one go about adding a second or third paginator to this view for a different doctrine entity?
Any help would be much apprieciated.
Thanks
Andrew
for that you have to use multiple addActionContext in init()
$this->_helper->ajaxContext->addActionContext('view', 'html')->initContext();
$this->_helper->ajaxContext->addActionContext('list', 'html')->initContext();
and you can continue
add action in controller as listAction() for paginator create file as list.ajax.phtml also and add required code inside them
This problem can be resolved if you manipulate the pagination links to let it call the other action.
For example: In the View Part, you can use the fourth parameter of the paginationControl method to define the links which refers to another action. This link should then be called in pagination_control.phtml.

Twitter Bootstrap and CodeIgniter's Validation_Errors

I am using Twitter Bootstrap to style validation_errors for a registration page:
<?php
echo "<div class='alert alert-error span4'>";
echo validation_errors();
echo "</div>";
?>
The validations work and show up but part of the styling is always present (the div tag has a red background). Is there a way to have the styling show up ONLY when the validation_errors are present. I have tried a few things (embedding html in php tags and enclosing the php in div tags) but the result is the same.
The reason that the div structure still appears is because it's echoing without regard to whether there are errors or not.
You could set the value of a variable to the result of your validation_errors() function in your Controller, then only display the alert div in your View if you've actually got an error...
Your controller would assign the variable to hold the (potential) error:
$this->data['reported_error'] = validation_errors();
$this->load->view('view_name', $this->data);
Then your view would only display the alert div if there was an error:
if ( isset($reported_error) )
{
echo "<div class='alert alert-error span4'>".$reported_error."</div>";
}
This requires your validation_errors function to only return a value if there is an error.
You can try something like this it works for me.
<?php if(validation_errors()):?>
<div class='alert alert-error span4'><?php echo validation_errors(); ?></div>
<?php endif;?>
I use the following construct to put the errors with special classes next to the fields that they reference:
<div class="<?php echo my_error_class('fieldname') ?>">
<input type="whatever" name="fieldname" />
<span class="whatever"><?php echo my_error_msg('fieldname') ?></>
</div>
with the following functions in a CI helper:
<?php
if ( ! function_exists('my_error_class')) {
function my_error_class($field, $error_class = "error") {
if (FALSE === ($OBJ =& _get_validation_object())){
return '';
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $error_class;
}
else {
return '';
}
}
}
if ( ! function_exists('my_error_msg')) {
function my_error_msg($field,$default = '') {
if (FALSE === ($OBJ =& _get_validation_object())){
return $default;
}
if(isset($OBJ->_field_data[$field]['error']) && !empty($OBJ->_field_data[$field]['error'])) {
return $OBJ->_field_data[$field]['error'];
}
else {
return $default;
}
}
}
I was having the same issue. I assigned validation_errors() to a variable in my controller and passed it to the view.
Going off James' solution, I had to change:
if ( isset($reported_error) )
to:
if (!empty($reported_error))
Once I did this, the alert block only displayed when there was an error.
I didn't find this in the guide but apparently validation_errors takes two optional args for a prefix and suffix... so you can do:
validation_errors('<p class="text-warning">', '</p>');

Categories