placeholder attribute in zf2 - php

How could insert the value of a field's db in the plcaholder in zf2
<div class="form_element">
<?php
$this->placeholder('name')->data = $this->data;
$name = $form->get('name');
echo $formLabel->openTag().$name->getOption('label')." ";
echo $this->formInput($name);
echo $formLabel->closeTag();
?>
</div>

A placeholder is a ViewHelper and therefore is is designed to help render view content.
In order to use your database data witin a placeholder you will need to ensure that the data is first passed to the view from the controller action.
public function modificaAlumnoAction()
{
//...
return ViewModel('data' => $data); // data passed to the view instance
}
Then within the view script
// modifica-alumno.phtml
$this->placeholder('foo')->data = $this->data;
An finally output the data (such as within the layout)
// layout.phtml
echo $this->placeholder('foo)->data;

Related

Values not passed from ctp file to controller in CakePHP

I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test

Codeigniter passing data controller to view

Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.
To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link
How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.

AJAX call to CodeIgniter controller with parameter

I know how AJAX call to CodeIgniter is working.
Edit for suggested answer
I tried redirection as a possible solution to my problem. I am not asking it as question. I am having problem passing parameter through URL and reusing view containing ajax post call. Also I am not aware how to post single value state_id which is already part of new_admission form.
I am loading city names for state_id of branch dynamically on $(document).ready()
When I call load_city() from admission() it works perfect.
XHR for load_city goes like:
localhost/project_folder/controller/load_city
But when I try edit_admission($studentId) it loads admission_view recursively inside <div id="city"></div>.
XHR for load_city goes like:
localhost/project_folder/controller/edit_admission/load_city
Here load_city is considered as parameter and edit_admission() is called recursively.
Controller:
public function load_city()
{
//load cities to $data from model
$this->load->view('city_view', $data);
}
public function admission()
{
//load init data for admission view from model
$this->load->view('admission_view', $data);
}
public function edit_admission($studentId)
{
//load init data for admission view from model
$this->load->view('admission_view', $data);
}
AJAX code:
function get_city() {
var parameters = {}; //instantiate the array
parameters['state_id'] = state_id;
$('#divcity').load('load_city', parameters, function (data) {
$('#city').combobox();
//code
});
};
load_city view:
<?php
echo '<select class="'.'form-control chzn-select col-lg-8 required'.'" id="'.'city'.'" name="'.'city'.'">';
echo '<option></option>';
foreach ($init_city['city_names'] as $row)
{
echo '<option value="'.$row->city_id.'">' .$row->city_name.'</option>';
}
echo '</select>';
?>
admission_view:
<div class="form-group">
<label class="control-label col-lg-4">City</label>
<div class="col-lg-8" id="divcity" name="divcity"></div>
</div>
I tried
public function edit_admission($studentId)
{
if(intval($studentId) > 0){
//load init data for admission view from model
$this->load->view('admission_view', $data);
} else if($studentId == 'load_city'){
//not passing post data to load_city()
redirect('branch/load_city');
}
}
Above code is not passing post data to load_city().
Also, I tried adding bellow code in routes.php
$route['edit_admission/load_city'] = 'load_city';
I did not get any success in both cases.

Is it possible to render a view to a rendered page from the controller using Yii?

It there any way to create a "placeholder" inside the main view file for rendering other view files with specified data using Yii?
I want to individually process data in the controller then place them to a specified location in the view file before rendering.
Here is a widget example:
The widget class:
class MyWidget extends CWidget
{
public $someData;
public $mainData;
public function init()
{
}
public function run()
{
$this->render('mainView',array('data'=>$someData));
foreach($data as $dat)
{
if(dat["color"]=="red")
{
$display = 4;
}
else if(dat["color"]=="blue")
{
$display = 6;
}
etc....
//this is the fictional method for that purpose
$this->addToPage('mainView','subView','placeholderName',
array('display'=>$display,'mainData'=>$main));
}
}
}
The mainView file:
echo("<div class='someDesign'>");
echo($data);
$this->placeholder('placeholderName');
echo("</div>");
The subView file:
if($display>0 && $display<=4)
echo("<div class='dataColorG'>");
else if($display>0 && $display<=4)
echo("<div class='dataColorD'>");
echo $mainData;
echo("</div'>");
The solution based on Nikola's answer:
The widget class:
class MyWidget extends CWidget
{
public $someData;
public $mainData;
public function init()
{
}
public function run()
{
$output ="";
foreach($data as $dat)
{
if(dat["color"]=="red")
{
$display = 4;
}
else if(dat["color"]=="blue")
{
$display = 6;
}
//If it's a widget we need to use $this->controller->renderPartial() instead of $this->renderPartial()
$output.= $this->controller->renderPartial('subView',array('display'=>$display,'mainData'=>$main),true);
}
$this->render('mainView',array('subView'=>$output,'data'=>$someData));
}
}
The mainView file:
echo("<div class='someDesign'>");
echo($data);
echo($subView); //the 'placeholder'
echo("</div'>");
The subView file:
if($display>0 && $display<=4)
echo("<div class='dataColorG'>");
else if($display>0 && $display<=4)
echo("<div class='dataColorD'>");
echo $mainData;
echo("</div'>");
You can use renderPartial for this purpose. You can place the code for renderPartial isntead $this->placeholder('placeholderName'); e.g.:
$this->renderPartial('placeholderView', array($data));
Chech the other params - you can save to string or process js/css from the partials.
You said "previously rendered file" which I interpret that you have the main file already in view in the browser, and then you would like to have new data processed by the controller and passed back the view, for which you would need an ajax call from the main view file somehow (maybe through an ajax button). If so have a look at CHtml::ajaxButton.
This allows you to call a controller action and push the resulting view to a DOM placeholder (using the HTML id). The replace key in ajaxOptions of CHtml::ajaxButton would replace the contents of the DOM placeholder. e.g.
'replace' => '#placeholder_id'
Edit
replace will actually replace the whole DOM element. If you want to replace the html content inside the DOM element you can use update key in ajaxOptions
<div id="subviewPlaceholder_id">html content</div>
Here is an example, which resides inside a form. The button push will send form data as get params. Use your controller action to read the params and $this->renderPartial('subView',array(... params ...)) to send back your sub view:
<?php
echo '<div id="subviewPlaceholder_id"></div>';
echo CHtml::ajaxButton('Get Sub View Button Name',array(
'controller/getSubView','param1'=>$presetParam),
array( // this is the ajaxOptions
'type'=>'GET',
'update'=>'#subviewPlaceholder_id', // id of DOM element for subview
), array( // this is the htmlOptions
'class'=>'normalButton',
));
?>
Added
If you would like to place a sub view inside another view at initial render. Use #Nikola's suggestion
$this->renderPartial('subView',array(...params...));
Example main view file (followed by subview file). Place both files in your view folder:
<?php // mainView.php
echo '<h1>MAIN VIEW</h1>';
echo '<div class="class">'.$mainData->attribute1.'</div>';
echo '<div class="class">'.$mainData->attribute2.'</div>';
// render anything else
// parameters for subView (processing should be done in controller actually)
$display = $condition==$criteria?1:2;
//this is where subview.php would be placed
//You could get '_subView' from a variable and switch your subView according
//to your criteria.
$this->renderPartial('_subView', array(
'display'=>$display,
'param2'=>$param2));
echo '<div>MAIN VIEW CONTINUED</div>'; // add any other rendering for main view
?>
And here is your sub view (prefix "_" for partial views by convention)
<?php // _subView.php
if($display>0 && $display<=4)
echo("<div class='dataColorG'>");
else if($display>0 && $display<=4)
echo("<div class='dataColorD'>");
echo $param2; // add anything else to be rendered.
echo "</div>";
?>

How to pass a variable from view to controller in codeigniter

I want to pass a language id for each link i click from my view to controller.
My view code is
<?php foreach ($languages as $lang) { ?>
<li>
</li>
<?php } ?>
My controller is
public function box($box_id=null, $language_name=null, $language_id=null) {
/// my function code
echo $box_id;
echo $language_name;
echo $language_id;
$data['languages'] = $this->Home_model->getLanguages($box_id);
}
The languages array contain the language id and language name
i want the name to be in url but not the id
The url looks like this
http://localhost/mediabox/home/box/12/en
if i send the language id in url it is then visible otherwise it is not visible in the controller.
How can I get language id for each link in controller without sending it in url
Thanks
pass the language name in the url without the ID, compare to languag_name column in table.
Lets assume you have url: http://localhost/mediabox/home/box/en
controller
<?php
# I wont write a controller but you should know how to do that, im also writing code as if you are just focusing on getting language.
public function box( /**pass in your other uri params as needed **/ $lang_name = 'en'){
#you could load this in the constructor so you dont have to load it each time, or in autoload.php if your using it site wide.
$this->load->model('lang_model', 'langModel');
#this example shows loading the library and running the function
$this->load->library('lang_library');
$this->lang_library->_getLang($lang);
#this example shows putting the getLang function inside the controller itsself.
self::_getLang($lang);
}
library/private function
<?php
private functon _getLang($lang = 'en'){
#run the query to retrieve the lang based on the lang_name, returns object of lang incl id
$lang = $this->langModel->getLang($lang_name);
if (!$lang){
die('language not found');
}else{
return $lang;
}
lang model
<?php
public function getLang($lang_name = 'en'){
$this->db->where('lang_name', $lang_name);
$this->db->limit(1);
$q = $this->db->get('languages');
if ($q->mysql_num_rows > 0){
return $q->result();
}else{
return false;
}
}
you will then have a variable with object associated to it then you can simply call $lang->lang_name; or $lang->lang_id;
Session storage
<?php
#you could call this in the beginning after using an ajax `$.post();` to retrieve the ID.. the easiest route though is whats above. I use this in my REST APIs
$this->session->set_userdata('lang', $lang);
Your confusion is in 'passing back' to the controller. Don't think of it as from controller => View (passing it say $data['something'] variables).
Its basically a <form>, so take a look at form helper and then at form validation.
That will give you an idea of how to create a form using codeigniter syntax.
In your controller, you would do a validation, and if it matches the language (or whatever you submit), then you can utilize sessions to save it for every page (so you don't need it in the URL).
Sessions are very simple and saving an item is as easy as:
$this->session->set_userdata('varname', 'value');
Later, on every other controller, you can check the variable
$language = $this->session->userdata('varname');
// load language etc;
Make a table with language ID and Language name in the database, just pass the language name to the controller and get the language ID by doing a db call.
You could do it using jQuery. Something like;
In View;
<ul id="language_selector">
<?php foreach ($languages as $lang) { ?>
<li>
<a href="javascript:;" class="change-language" data-language="<?php echo $lang['language_name']?>" data-box="<?php echo $template_data['box_id']?>">
<img src="<?php echo base_url(); ?>public/default/version01/images/country_<?php echo $lang['language_name'] ?>.png" width="27" height="18" border="0" />
</a>
</li>
<?php } ?>
</ul>
The JS;
$(function() {
$('.change-language').live('click', function() {
var language_name = $(this).data('language');
var box_id = $(this).data('box');
$.ajax({
url: '/home/box/'+language_name,
type: 'post',
data: 'box_id='+box_id,
success: function( data ) {
self.parent.location.reload();
},
error: function( data ) {
alert('oops, try again');
}
});
});
});
The controller:
public function box($language) {
$box_id = $this->input->post('box_id');
// do a llokup on the language as suggested by #vivek
}
You are telling CodeIgniter that you will be receiving both the language name and id in your action.
public function box($box_id=null, $language_name=null, $language_id=null) {
}
Change that to just
public function box($box_id=null, $language_name=null) {
}
For your example URL you should then get $box_id == 12 and $language_name == 'en'.
Then lookup the language id by using it's name either in a helper or as part of a Language model as Mike suggests.

Categories