I am trying to call an external function within a class method property. It actually does gets called but at the end of the page and whatever is inside the method property, remains separate.
Since I am a self taught student, it is recent that I have started learning PHP classes so I am not really sure if this can be done or not.
Please guide me how this can be done correctly or if not, then what could be the workaround?
The class I have written is as follows:
It will take the input from user while creating of instance and render a modal box based on the input and options selected.
class modalBox{
private $modal_id, $modal_anim, $header_title, $modal_content,$footer;
private $headerOpt,$titleOpt,$footerOpt,$closeBtn;
public function setID($id){
$this->modal_id = $id;
}
public function getID(){
$modal_id = $this->modal_id;
return $modal_id;
}
public function setTitle($title){
$this->header_title = $title;
}
public function getTitle(){
$title = $this->header_title;
return $title;
}
public function setBodyContent($content){
$this->modal_content = $content;
}
public function getBodyContent(){
$modalContent = $this->modal_content;
return $modalContent;
}
public function setFooterContent($footer){
$this->footer = $footer;
}
public function getFooterContent(){
$footerContent = $this->footer;
return $footerContent;
}
public function initiateModal($modal_anim, $headerOpt, $titleOpt, $closeX, $footerOpt, $footerCloseBtn){ ?>
<div class="modal <?php if($modal_anim != 'false'){echo $modal_anim;} ?>" id="<?php echo $this->getID(); ?>" style="z-index: 2;">
<div class='modal-dialog'>
<div class='modal-content'>
<?php
// display if header option is set to true
if ($headerOpt){
?>
<div class="modal-header">
<h4><?php echo $this->getTitle(); ?></h4>
<?php
// display if close button (X) is set to true
if($closeX){
?> <button type="button" class="close" data-dismiss="modal">×</button> <?php } ?>
</div>
<?php } ?>
<div class="modal-body"><?php echo $this->getBodyContent(); ?></div>
<?php if($footerOpt){ ?>
<div class="modal-footer"><?php echo $this->getFooterContent(); ?>
<?php if($footerCloseBtn){ ?>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
}
}
?>
The function I am trying to call within property is as follows;
This function is not inside a class. This is present independently in functions.php which I have included in index file.
function getDocNameList() {
global $db;
$getDoc = $db->prepare("SELECT id,doc_name from doctor");
$getDoc->execute();
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
// print the returned rows in options list of <select>
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
}
The initiation of class instance is as follows, Please note where I am calling the function
// create class instance
$rangeModal = new modalBox;
//set the modal id
$rangeModal->setID ("rangeFields");
//set the modal title in header
$rangeModal->setTitle("Select Date Range");
// set the body content
$rangeModal->setBodyContent("
<form method='post' action='expenditure.php'>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker1' name='exp_date_from' value='From Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker2' name='exp_date_to' value='To Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<select>" . getDocNameList() . "</select>
</div>
");
//set the footer content
$rangeModal->setFooterContent("
<input type='submit' class='btn btn-success' name='submitRange' />
</form>
");
/*
* #args ---
* modal animation
* modal header (boolean)
* modal title (boolean)
* modal close X (boolean)
* modal footer (boolean)
* modal footer close button (boolean)
*/
// initiate modal
$rangeModal->initiateModal('fade',true,true,true,true,true);
I expect the output of the function to be displayed as .... within the block but instead it gets rendered at the bottom of the page just before tag.
You echo it here, so it will be displayed immediately:
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
So it is not concatenated here, the function does not return anything:
<select>" . getDocNameList() . "</select>
Build it and return it instead:
$output = '';
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output .= "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return $output;
Or build an array and join the elements:
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output[] = "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return implode($output);
Related
I would like the below php functions to check for multiple product id's !== (1427, 1428, 1429).
I tried adding:
$ids = array(1427, 1428, 1429)
if (in_array($product->get_id(), $ids) { }
But it did not work.
What is the best approach?
Thank you.
//add multistep
add_action('wapf_before_wrapper', 'wapf_before_wrapper');
function wapf_before_wrapper($product) {
if($product->get_id() !==1427)
return;
?>
<div class="wapf-progress">
<div class="wapf-progress-bar"></div>
<div class="wapf-progress-steps"></div>
</div>
<?php
}
add_action('wapf_before_product_totals', 'wapf_before_product_totals');
function wapf_before_product_totals($product){
if($product->get_id() !==1427)
return;
?>
<div class="wapf_step_buttons">
<button class="button wapf_btn_prev" style="display:none">Previous</button>
<button class="button wapf_btn_next">Next</button>
</div>
<?php
}
//end multistep
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here
I have a page with Groups of Teams which has delete team button next to it.
When team is not in group it has checkbox and button to add team to group.
I wrote in actionView that will render a list of groups with teams.
actionView in GroupController
public function actionView($id) {
$group = $this->loadModel($id);
$teamlst = Group::getAllTeamOfGroup($id);
$teamnotlst = Group::getAllTeamNotInGroup($id);
// Submit
$preSelectedItems = array();
if (isset($_POST['teamlist'])) {
$preSelectedItems = array();
foreach ($_POST['teamlist'] as $selectedItem) {
$preSelectedItems[] = $selectedItem;
}
}
// $teamNo = CHtml::listData($teamnotlst, 'id', 'name');
//Delete
$this->render('view', array(
'model' => $group,
'teamlst' => $teamlst,
'preSelectedItems'=> $preSelectedItems,
'group_id'=>$id,
'teamnotlst' => $teamnotlst,
));
if(isset($_POST['btndeleteteam'])){
TeamGroup::model()->deleteTeamGroup($team->id, $model->ID);
}
}
in view file
<div class="action">
<input type="submit" name="btnupdateteam" value="Update Team">
</div>
<?php echo CHtml::endForm(); ?>
<div class ="team">
<div class="column1">
<?php foreach ($teamlst as $team): ?>
<div class="row">
<?php
echo $team->name;
?>
<input type="submit" name="btndeleteteam" value="Delete Team">
<?php
if(isset($_POST['btndeleteteam'])){
TeamGroup::model()->deleteTeamGroup($team->id, $model->ID);
}?>
</div>
</div><!-- comment -->
<?php endforeach; ?>
<?php
$preSelectedItems = array();
if (isset($_POST['teamlist'])) {
$preSelectedItems = array();
foreach ($_POST['teamlist'] as $selectedItem) {
$preSelectedItems[] = $selectedItem;
}
}
$teamNo = CHtml::listData($teamnotlst, 'id', 'name');
echo CHtml:: checkBoxList('teamlist', $preSelectedItems, $teamNo);
?>
</div>
<div class ="team available">
</div>
My idea is that when you click delete team button it will delete team from group and I has a method for this
TeamGroup::model()->deleteTeamGroup($team->id, $model->ID);
When team not in group it will has checkbox and update button that will add team to group if checkbox is checked.
Thank for advance!
if i understand right what is your problem then you need to read this doc chapter
http://www.yiiframework.com/doc/guide/1.1/en/basics.controller#action
all your actions i.e. delete or add must reside in controller and not in view
instead of this in view:
if(isset($_POST['btndeleteteam'])){
TeamGroup::model()->deleteTeamGroup($team->id, $model->ID);
}?>
you must add something like this into controller
public function actionDelete($id) {
TeamGroup::model()->deleteTeamGroup($id);
$this->redirect('group/view');
}
and instead of this
<input type="submit" name="btndeleteteam" value="Delete Team">
something like this must be in a view
delete
or you can modify CGridView to suite your needs
I have create a web application using CodeIgniter making at first a login interface. Here are the controller I used but I think something doesn't work but I don't know what.The home page, where the user is granted, it doesn't show.Unfortunately I didn't have a debugger to check what doesn't work. maybe there is a problem to handle the session but really I don't know what can be. maybe you are smarther than me to find the error
Login Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('User','user'); /* This call the model to retrieve data from db */
}
public function index()
{
if(!file_exists('application/views/_login.php'))
{
show_404();
}
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 style="text-align:center;">','</h4>');
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|xss_clean|callback_pass_check');
if($this->form_validation->run() == FALSE)
{
/* Data to pass to view */
$data['title'] = "User Access";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header',$data);
$this->load->view('_login',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('home', 'refresh');
}
}
public function pass_check($pass)
{
$result = $this->user->find_user($this->input->post('username'),$pass);
if(!empty($result))
{
foreach ($result as $row)
{
$session_array = array('id'=> $row->id, 'username'=> $row->username); /* Create a session passing user data */
$this->session->set_userdata('logged_in', $session_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('pass_check',"Invalid username or password!</br>Try again, please!");
return FALSE;
}
}
}
/* END OF FILE */
Home Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
session_start();
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['title'] = "Management Emergency";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header', $data);
$this->load->view('_home',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('login', 'refresh');
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home','refresh');
}
}
/* END OF FILE */
The model in the login controller works very well so It isn't a problem of query. Before adding session everything works but when I added session stopped to worked so I think that can be a problem or redirect() or session
Home View
<div data-role = "page">
<div data-role = "header" data-position = "inline">
<?php echo heading($title,1) ?>
</div>
<div class = "menu-content">
<ul data-role = "listview" data-inset="true">
<li data-role = "list-divider">Emergency Menù</li>
<li class = "menu-item">
<a href="">
<div class = "image-wrapper">
<img src="/assets/images/user.png" class = "ui-li-icons" />
</div>
Add patient
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/home.png" class = "ui-li-icons" />
</div>
Show all hospital
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/favorite.png" class="ui-li-icons" />
</div>
Find patients
</a>
</li>
<li class="menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/email.png" class="ui-li-icons" />
</div>
Send medical infos
</a>
</li>
</ul>
Login View
<div data-role ="dialog">
<div data-role = "header" data-theme="e">
<?php echo heading($title,1) ?>
</div>
<div data-role ="content">
<?php
$var = validation_errors();
if(!empty($var))
{
echo form_error('username');
echo form_error('password');
}
else
{
echo heading('911 - First Aid',2,'style="text-align:center; color:red;"');
echo form_open('login');
?>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="name" value="" placeholder="Username"/>
</div>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
</div>
<div data-role ="fieldcontain">
<input type="submit" value="Login" data-theme ="b"/>
</div>
</form>
<?
}
?>
There is a problem with CodeIgniter retaining it's session data after a redirect. Your if($this->session->userdata('logged_in')) in your home.php controller will evaluate false every time because the session is resetting. You could use the native php sessions to skip over this problem.
See: http://codeigniter.com/wiki/Native_session/. Good luck!
UPDATE
Apparently, this is only true of CodeIgniter 1.7.2 when used with IE6. It doesn't affect most browsers.
open the application/config/autoload.php file and add the 'url' in the helper array;
$autoload['helper'] = array('url');
i hope this will help you to fix the problem.
in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>