Codeigniter 3 - how to add option with possible select template - codeigniter-3

I've created table in database:
general_settings -> template -> layout01
in storefront dropdown with possible select layout01, layout02, layout03 etc with post value to database.
and now styles, js etc:
assets/frontend/layout01
assets/frontend/layout02
assets/frontend/layout03
etc.
and currently I can only load one template layout01 example like this:
in
application/views/index.php
application/views/partials/_header.php
application/views/partials/_footer.php
and in Home_Controller.php I call this like this:
public function index()
{
$this->load->view('partials/_header', $data);
$this->load->view('index', $data);
$this->load->view('partials/_footer');
}
How to load styles and _header.php, _footer.php and all others pages depending on value in database layout01, layout02 etc?

In the header and footer files make a simple function call which you can do in helper with a readdir/scandir etc. In the header you load the assets/frontend/$selected_layout/.css files, while in the footer you load the assets/frontend/$selected_layout/.js files.
application/helper/loadResources_helper.php
<?php
function loadResources($layout, $type)
{
$files = [];
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./assets/frontend/'.$layout.'/'));
foreach ($rii as $file) {
if ($file->isDir()){
continue;
}
$ext = $file->getExtension();
if($type == $ext) {
$files[] = $file->getPathname();
}
}
return $files;
}
then we load the helper for automatic loading
application/config/autoload.php
$autoload['helper'] = array('...','....','loadResources');
application/views/partials/_header.php
foreach(loadResources($selected_layout, 'css') as $stylesheet) {
echo '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />';
}
application/views/partials/_footer.php
foreach(loadResources($selected_layout, 'js') as $javascript) {
echo '<script type="text/javascript" src="'.$javascript.'"></srcipt>';
}
$selected_layout = your SQL query for general_settings -> template -> layoutXX

Related

output records in the form of html table from moodle database , custom block development

Please check this code for the custom block to be placed in the dashboard. We want to display an HTML table for the records. But it does not add up to the custom block, rather it appears on the top page.
enter image description here
class block_scorecard extends block_base {
function init() {
$this->title = get_string('pluginname', 'block_scorecard');
}
function get_content() {
global $DB;
if ($this->content !== NULL) {
return $this->content;
}
$content = '';
$courses = $DB->get_records('scorm_scoes_track', ['element' => 'cmi.core.total_time']);
$table=new html_table();
$table->head=array('No of attempts','Time modified','status');
foreach ($courses as $course) {
$attempt=$course->attempt;
$timemodified=userdate($course->timemodified, get_string('strftimerecentfull'));
$status=$course->value;
$table->data[]=array($attempt, $timemodified, $status);
}
echo html_writer::table($table);
$this->content = new stdClass;
$this->content->text = $content;
}}
echo html_writer::table($table);
Should be
$content .= html_writer::table($table);

Zend : Error Occurs when create html file from zend phtml file for multiple employee

//controller function
function sendBulkMailAction(){
$template = "estimated-festival-bill-single.phtml";
foreach ($employeeArr as $profile_id => $employeeValue) {
$someData = array(); //here include some salary data
$model = new ViewModel($someData);
$model->setTemplate($template);
$htmlContent = "<!DOCTYPE html>\n\r<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\r<head>
<meta charset=\"utf-8\">
</head>
<body>"
. $this->getServiceLocator()->get('viewrenderer')->render($model)
. "</body>
</html>";
//create html file
//create pdf link from html by wkhtmlToPdf
//send this link via email to employee
}
}
//estimated-festival-bill-single.phtml
//simple code
<div> Employee Name</div>
<br>
<div><?php echo _get_salary_html(); ?></div>
<?php
function _get_salary_html(){
return "Salary Data";
}
?>
error show
Fatal error: Cannot redeclare _get_salary_html() (previously declared in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml:9) in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml on line 10
hints: when single employee its ok but for multiple employee show error
Because you are re-declaring function unknowingly. Add a condition around the function like below.
if (!function_exists('_get_salary_html')) {
function _get_salary_html() {
........
}
}

Convert a php script to codeigniter 3

Please i am working on a project and need to generate pincode per request. This is the script i have for php but i need to implement codeigniter 3. Also please can i set it in such a way that if i want 10 pin i input 10 and generate 10 into the database and if want 50 i input 50. i am new to codeigniter 3 and i have read the tutorials but doesnt seems to help on this.
Here is my code on php
Please i want to be able to generate base on the number i want per request.
<?php
$connect = mysqli_connect("localhost","hadassa","root", "")
or die("Cannot connect");
$digits = 5;
function gen_ran($digits) {
$n = "";
for ($x = 1; $x <= $digits; $x++) {
$n.=mt_rand(0,9);
}
return $n;
}
function gen_ran2($digits)
{
$n2 = "";
for($a=1; $a<=$digits; $a++)
{
$n2 .=mt_rand(0,9);
}
return $n2;
}
for($a=1; $a<=20; $a++)
{
$codes = gen_ran($digits) . gen_ran2($digits);
$query = "INSERT INTO pin (pin)
VALUES ('$codes')";
$result = mysqli_query($connect, $query)
or die("Error");
if($result)
echo"$codes<br>";
}
?>
<script type="text/javascript">
alert("PIN Generated Successfully");
window.location = "#";
</script>
codeignater use the MVC So
create a controller in controller folder to write logic
create a model in models folder for write database code
in the viewer, folder create a view for the user view code
https://www.youtube.com/watch?v=K71j-rWXejk&index=2&list=PLUpnKy5Si8zDouvZiUMHwSSyVrowJmH22
https://www.youtube.com/watch?v=IOZqRgOgSu4

How to use Zend ProgressBar in a Zend MVC application

I've been trying to use the JsPush Zend progress bar in a Zend MVC application, but have not been successful. I've used the JsPush.php example found on github to create a standalone progress bar test application, but this does not use the Zend MVC framework. When I apply the CSS, HTML, JavaScript, and PHP code from the JsPush example program, I see my progress bar appear (the CSS works) but I don't get any results during my socket write process. I've used the JsPush CSS code verbatim in a css file that is linked to my application so I won't repeat that here. Below are exerpts from my MVC application, the controller code:
protected function _sendFile($job)
{
$fp = fopen($job->source_file, "rb");
if($fp == null || $fileData['size'] == 0) {
$this->view->errorMessage = 'Error - file open failed for ' . $job->source_file;
return false;
}
$this->totalXmitSize = $fileSize;
$this->currentXmitSize = 0;
$progressMessage = '';
$adapter = new Zend_ProgressBar_Adapter_JsPush(array
('updateMethodName' => 'Zend_ProgressBar_Update',
'finishMethodName' => 'Zend_ProgressBar_Finish'));
$progressBar = new Zend_ProgressBar($adapter, 0, $this->totalXmitSize);
while(!feof($fp)) {
$blkSize = ($fileSize > 1024) ? 1024 : $fileSize;
$xmitBuf = fread($fp, $blkSize);
if($xmitBuf === false || !strlen($xmitBuf)) {
$this->view->errorMessage = 'Error - file open failed for ' . $job->source_file;
return false;
}
if($this->_writeData($xmitBuf, $blkSize) == false) {
return false;
}
$fileSize -= $blkSize;
$this->currentXmitSize += $blkSize;
$progress = $this->_calculateXmitProgress();
if($progress < 25) {
$progressMessage = 'Just beginning';
} elseif($progress < 50) {
$progressMessage = 'less than half done';
} elseif($progress < 75) {
$progressMessage = 'more than half done';
} else {
$progressMessage = 'almost done';
}
$progressBar->update($this->currentXmitSize, $progressMessage);
if($fileSize <= 0) {
break;
}
}
fclose($fp);
$xmitBuf = '';
$bufLen = 0;
if($this->_readData($xmitBuf, $bufLen) === false) {
return false;
}
$progressBar->finish();
if(strncmp($xmitBuf, MSG_STATUS_OK, strlen(MSG_STATUS_OK)) != 0) {
$this->view->errorMessage = 'Error - invalid response after file transfer complete';
return false;
}
return true;
}
The view code:
<?php
$this->title = "My Title";
$this->headTitle($this->title);
$this->layout()->bodyScripts = 'onload="startProgress();"';
?>
<p class="errors"> <?php echo $this->errorMessage ?> </p >
<?php echo $this->form->setAction($this->url());
?>
<div id="progressbar">
<div class="pg-progressbar">
<div class="pg-progress" id="pg-percent">
<div class="pg-progressstyle"></div>
<div class="pg-invertedtext" id="pg-text-1"></div>
</div>
<div class="pg-text" id="pg-text-2"></div>
</div>
</div>
<div id="progressBar"><div id="progressDone"></div></div>
The layout.phtml code:
function startProgress()
{
var iFrame = document.createElement('iframe');
document.getElementsByTagName('body')[0].appendChild(iFrame);
iFrame.src = 'MyController.php';
}
function Zend_ProgressBar_Update(data)
{
document.getElementById('pg-percent').style.width = data.percent + '%';
document.getElementById('pg-text-1').innerHTML = data.text;
document.getElementById('pg-text-2').innerHTML = data.text;
}
function Zend_ProgressBar_Finish()
{
document.getElementById('pg-percent').style.width = '100%';
document.getElementById('pg-text-1').innerHTML = 'done';
document.getElementById('pg-text-2').innerHTML = 'done';
}
</script>
</head>
<body <?php echo $this->layout()->bodyScripts ?>>
<div>
<h1><?php echo $this->escape($this->title); ?></h1>
<?php echo $this->layout()->content; ?>
</div>
When this runs I get a ton of JavaScript in the page source, but no progress results:
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":0,"max":3397,"percent":0,"timeTaken":0,"timeRemaining":null,"text":null});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":1024,"max":3397,"percent":30.14424492199,"timeTaken":0,"timeRemaining":0,"text":"less than half done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":2048,"max":3397,"percent":60.28848984398,"timeTaken":0,"timeRemaining":0,"text":"more than half done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":3072,"max":3397,"percent":90.43273476597,"timeTaken":0,"timeRemaining":0,"text":"almost done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Update({"current":3397,"max":3397,"percent":100,"timeTaken":0,"timeRemaining":0,"text":"almost done"});</script><br />
<script type="text/javascript">parent.Zend_ProgressBar_Finish();</script><br />
All of this JavaScript pushes my form out of view. I have spent days on the Zend documentation site and scouring the web to find examples of someone successfully using Zend ProgressBar in a MVC framework application, but can not find any working examples. Thanks in advance for any help.
Well I have been successful in getting a JsPush progress bar to work to some degree, but not 100% correct for my application.
The progressbar works, but the form results end up in the hidden iframe. There is no way to get to the submit buttons on that iframe, so my user has to use the back button to get out of the form.
The only way to get the progress bar to work is to use the target attribute in the form and assign it to the name attribute of the iframe. If I don't use the target attribute, the form scrolls for every call to progressBar->update;. So my form results end up on the parent page several hundred lines scrolled down and the scroll bar never works.
I've tried using the example from the Zend documentation, but it doesn't work. This is my first venture into the Zend framework and it has been very frustrating and disappointing. Not a single response to my original question from 28 days ago.
I had same problem. For me it worked since I did the following steps.
Go to the php.ini and check if the following Data is set in your php.ini.
output_buffering = Off
;output_handler =
zlib.output_compression = Off
;zlib.output_handler =
Then go to class Zend_ProgressBar_Adapter_JsPush and find the Method - which is at the bottom - _outputData. Delete everything in this Method and input
// 1024 padding is required for Safari, while 256 padding is required
// for Internet Explorer. The <br /> is required so Safari actually
// executes the <script />
echo str_pad($data . '', 1024, ' ', STR_PAD_RIGHT) . "\n";
echo(str_repeat(' ',256));
if (ob_get_length()){
#ob_flush();
#flush();
#ob_end_flush();
}
#ob_start();

Zend_Form_Element_MultiCheckbox: How to display a long list of checkboxes as columns?

So I am using a Zend_Form_Element_MultiCheckbox to display a long list of checkboxes. If I simply echo the element, I get lots of checkboxes separated by <br /> tags. I would like to figure out a way to utilize the simplicity of the Zend_Form_Element_MultiCheckbox but also display as multiple columns (i.e. 10 checkboxes in a <div style="float:left">). I can do it manually if I had an array of single checkbox elements, but it isn't the cleanest solution:
<?php
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
?>
<div id="checkboxes">
<?php foreach ($columns as $columnOfCheckboxes): ?>
<div style="float:left;">
<?php foreach($columnOfCheckboxes as $checkbox): ?>
<?php echo $checkbox ?> <?php echo $checkbox->getLabel() ?><br />
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
How can I do this same sort of thing and still use the Zend_Form_Element_MultiCheckbox?
The best place to do this is using a view helper. Here is something I thought of really quickly that you could do. You can use this in your view scripts are attach it to a Zend_Form_Element.
I am going to assume you know how to use custom view helpers and how to add them to form elements.
class My_View_Helper_FormMultiCheckbox extends Zend_View_Helper_FormMultiCheckbox
{
public function formMultiCheckbox($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
// zend_form_element attrib has higher precedence
if (isset($attribs['listsep'])) {
$listsep = $attribs['listsep'];
}
// Store original separator for later if changed
$origSep = $listsep;
// Don't allow whitespace as a seperator
$listsep = trim($listsep);
// Force a separator if empty
if (empty($listsep)) {
$listsep = $attribs['listsep'] = "<br />\n";
}
$string = $this->formRadio($name, $value, $attribs, $options, $listsep);
$checkboxes = explode($listsep, $string);
$html = '';
// Your code
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
foreach ($columns as $columnOfCheckboxes) {
$html .= '<div style="float:left;">';
$html .= implode($origSep, $columnOfCheckboxes);
$html .= '</div>';
}
return $html;
}
}
If you need further explanation just let me know. I did this fairly quickly.
EDIT
The reason I named it the same and placed in a different directory was only to override Zend's view helper. By naming it the same and adding my helper path:
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
My custom view helper gets precedence over Zend's helper. Doing this allowed me to test without changing any of my forms,elements, or views that used Zend's helper. Basically, that's how you replace one of Zend's view helpers with one of your own.
Only reason I mentioned the note on adding custom view helpers and adding to form elements was because I assumed you might rename the helper to better suit your needs.