I have one team array and want that team name every where to show team name.It is possible to built a global function which can return team name and I call that function from my view means ctp file.
please try this for west:
<?php
// controller name like app,users
// action name like getdata should be in controller
// and you can send parameter also
$output = $this->requestAction('controllerName/actionName/'.$parameter);
?>
There are multiple approaches to this. What I cannot tell from your description is exactly what you are looking for. If it is simply to create an array of items that is accessible in your views, I would put it in app_controller.php
var $teams = array('team1', 'team2', 'team3');
beforeFilter() {
$this->set('teams', $this->teams);
}
Then in your view, you can access the array by the variable: $teams
If you only want to call teams on certain views, it may not be a good idea to set this variable for EVERYTHING. You can get around it by setting up a function in app controller.
function get_teams_array() {
$teams = array('team1', 'team2', 'team3');
return $teams;
}
Then put together an element that will call this function:
views/elements/team.ctp
<?php
$teams = $this->requestAction(
array('controller' => 'app', 'action' => 'teams'),
array('return')
);
/** process team array here as if it were in the view **/
?>
Then you can just call the element from your view:
<?php echo $this->element('team'); ?>
You can add in your /app/config/bootstrap.php file something like:
Configure::write('teams', array('team1', 'team2'));
Then everywhere you can get that array with:
$teams = Configure::read('teams');
and use it.
In CakePHP 3.*, you can use Helpers.
https://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers
1 - Create your helper inside src/View/Helper:
/* src/View/Helper/TeamHelper.php */
namespace App\View\Helper;
use Cake\View\Helper;
class TeamHelper extends Helper
{
public function getName($id)
{
// Logic to return the name of them based on $id
}
}
2 - Once you’ve created your helper, you can load it in your views.
Add the call $this->loadHelper('Team'); inside /src/View/AppView.php:
/* src/View/AppView.php */
class AppView extends View
{
public function initialize()
{
parent::initialize();
$this->loadHelper('Team');
}
}
3 - Once your helper has been loaded, you can use it in your views:
<?= $this->Team->getName($id) ?>
Related
Data are stored as ["item_1", "item_2"] in database like shown below.
I want to display those data in view blade properly.
Product Model
protected $fillable = ['name', 'prod_id'];
public function models() {
return $this->hasMany(Model::class, 'prod_id');
}
Model Model
protected $fillable = ['model', 'prod_id'];
protected $cat = ['model'=>'array'];
public function model()
{
return $this->belongsTo(Product::class, 'prod_id');
}
Controller - store method
public function create (Request $request, Product $product){
$models = new Model;
{
$model = json_encode(request('models'));
$items->models = $model;
$product->models()->save($models);
}
}
Controller show method
public function show(request $id){
$product = Product::findorfail($id);
$models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product', 'models'));
Create View
<input type="checkbox" name="model[]" value="Samsung">
<input type="checkbox" name="model[]" value="Nokia">
<input type="checkbox" name="model[]" value="Apple">
<button>Add Model</button>
I tried show view:
#foreach($models as $model)
{{ json_decode($model->models) }}
#endforeach
It throws
htmlspecialchars() expects parameter 1 to be string, array given
What am I missing.
PS: MySQL does not support json column, so I saved as text column.
you need to do someting like this.
Model Model
protected $fillable = ['models', 'prod_id']; // screenshot says that the field name is "models"
protected $cast = ['models' => 'array']; // the property is $cast no $cat
public function product()
{
return $this->belongsTo(Product::class, 'prod_id');
}
ModelController - store method
public function store (Request $request){
$product = Model::create([
'models' => json_encode($request->models),
'prod_id' => $request->prod_id
]);
return redirect()->back()->with('success', 'created!');
}
public function show(Request $id){
$model = Model::findOrFail($id)->with('product');
return view ('model.show', compact('model'));
}
ProductController show method
public function show(request $id){
$product = Product::findOrFail($id)->with('models'); // the method name is findOrFail() no findorfail
// $models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product'));
}
Into the show View
#foreach($product->models as $models)
#foreach(json_decode($models->models) as $model)
{{ $model }}
#endforeach
#endforeach
Your Models Model confuses me a little bit. You seem to have a field name model that's the same as a relationship method name. That means whenever you include that relation, it'd functionally override that property with data from the related table. (I say 'functionally' because you're using dynamic properties, whereas it is actually possible to explicitly tell Eloquent whether you want an attribute or relation without making it guess.)
That said, your $model->models property could be coming back as an array for one of two reasons. The first is that it may be accidentally referring to a relational data-set and not the JSON string you were expecting. The second is you've corrected the protected $cat = ['model'=>'array']; to read protected $cast = ['models'=>'array'];, and it's stepping on your toes now. By casting it to an array, it may be getting automatically get interpreted back into one before you call json_decode on it.
Either way, I'd dd($model->models) to see what it is first.
You need to change your foreach like this:
#foreach($models->models as $model)
{{ json_decode($model) }}
#endforeach
because Your array is like this
{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}
In here the $models is getting only id and prod_id models is still array so your foreach should be #foreach($models->models as $model)
Sample Code is here:
$arr = '{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}';
echo '<pre>';
foreach (json_decode($arr->models) as $str){
echo $str;
}
The question i am asking is very similar and already asked question.But It is working for me.
ViewReportsController.php
class ViewReportsController extends AppController {
public function index() {
$count_table = 10;//sample variable that is available in view
$this->set('count_tablen',$count_table);
}
}
APP/View/Layouts/default.ctp
pr($count_tablen);
Now i am getting the error says- Undefined variable: count_tablen [APP/View/Layouts/default.ctp, line 228]
You are using a variable in your main layout template which is likely used by multiple controller actions. Therefore, the code example you've provided would only work on /view_reports/index. If you want to set variables to be used in the layout templates you need to do this in the beforeRender callback of AppController so that it can be used everywhere:-
public function beforeRender() {
parent::beforeRender();
$count_table = 10;
$this->set('count_tablen', $count_table);
}
If you use multiple layout templates you can check which template will be used in beforeRender before setting the variable:-
public function beforeRender() {
parent::beforeRender();
if ($this->layout === 'default') {
$count_table = 10;
$this->set('count_tablen', $count_table);
}
}
I am trying to retrieve data from another controller to display it in the PagesController's view using an element. I have a table
service_categories(id, service_category);
my ServiceCategoriesController looks like this
public function category() {
$serviceCategories = $this->paginate();
if ($this->request->is('requested')) {
return $servicesCategories;
} else {
$this->set('serviceCategories', $servicesCategories);
}
}
my category.ctp element looks like this
<?php
$serviceCategories = $this->set('serviceCategories/category');
foreach ($serviceCategories as $serviceCategory):
echo $serviceCategory['ServiceCategory']['service_category'];
endforeach;
But I seem to get an undefined value of "$serviceCategories" when I create an alert before the foreach loop. Please assist! What am I missing?
I rewrite the answer after turning on brain:
In your element replace:
$serviceCategories = $this->set('serviceCategories/category');
with
$serviceCategories = $this->requestAction('service_categories/category');
This might be a naive question since I am new to cakephp.
I am working on a project where there are many layouts, helpers and elements. Because this is a mutli-language site, I am intercepting the final rendered output to do some language conversion(so each visitor only sees his native language on the site including user input).
I've managed to convert most of the layouts and helpers by adding code in two places: AppController's afterFilter() and AppHeler's afterRender() function. But I can't figure out a centralized way to handle the elements and there are dozens of them.
So here are my questions: do all elements in cakephp have a common ancestor class? If so, does this ancestor class have callback functions like afterRender()?
Many thanks!
I'm not sure such a callback exists specific for 'elements', but looking at the source code, View::element() renders an element using the same _render() method as the View itself, and should trigger beforeRender() and afterRender()
Creating a custom View Class and Custom Callbacks
You may use a custom 'View' class and override the element() method, for example to have your own 'custom' callbacks being triggered in helpers
Something like this;
app/view/app_view.php
class AppViewView extends View {
/**
* custom 'element()' method, triggers custom
* before/aferRenderElement callbacks on all loaded helpers
*/
public function element($name, $params = array(), $loadHelpers = false)
{
$this->_triggerHelpers('beforeRenderElement');
$output = parent::element($name, $params, $loadHelpers);
$this->_triggerHelpers('afterRenderElement');
}
/**
* Names of custom callbacks
*/
protected $_customCallBacks = array(
'beforeRenderElement',
'afterRenderElement',
);
function _triggerHelpers($callback)
{
if (!in_array($callback, $this->_customCallbacks)) {
// it's a standard callback, let the parent class handle it
return parent::_triggerHelpers($callback);
}
if (empty($this->loaded)) {
return false;
}
$helpers = array_keys($this->loaded);
foreach ($helpers as $helperName) {
$helper =& $this->loaded[$helperName];
if (is_object($helper)) {
if (
is_subclass_of($helper, 'Helper')
&& method_exists($helper, $callback)
) {
$helper->{$callback}();
}
}
}
}
}
Then, in your AppController specify the 'view' class to use;
class AppController extends Controller {
public $view = 'AppView';
}
I have the following form:
<?php
class Application_Form_RegistrationForm extends Zend_Form{
public function init(){
$country = $this->createElement('select', 'country');
$country->setLabel('country: ')
->setRequired(true);
$email = $this->createElement('text', 'email_address');
$email->setLabel('Email Address: ')
->setRequired(true);
$register = $this->createElement('submit', 'register');
$register->setLabel('Create new Account')
->setIgnore(true);
$this->addElements(array(
$country, $email, $register
));
}
}
?>
The list of the countries are present in a table country in a database.
Is there anyway I can populate the country dropdown list with the country names from the database?
Any help is appreciated.
Thanks
You sure can.
In the init method you can set the options with something like this, assuming $db is a Zend_Db adapter:
$options = $db->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
$country->setMultiOptions($options);
In case you haven't seen the fetchPairs method, it builds an array, where the first column return becomes the key, and the second column the value.
You could do it from controller's action (or even in Service Layer, if to be meticulous), if your list's content depends from some conditions.
Usage:
$form->getElement('country')->addMultiOption('1','USA'); //add single value
$form->getElement('country')->addMultiOptions(array('1'=>'USA', '2'=>'Canada')); //add values by array
$form->getElement('country')->setMultiOptions(array('1'=>'USA', '2'=>'Canada')); //set values by array
Of course, to add values from DB you need to fetch them first.
See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.select for more methods available.
The best way is to create a new class for the element:
Put this in "/application/form/element/CountySelect.php"
class Application_Form_Element_CountrySelect extends Zend_Form_Element_Select {
public function init() {
$oCountryTb = new Application_Model_Country();
$this->addMultiOption(0, 'Please select...');
foreach ($oCountry->fetchAll() as $oCountry) {
$this->addMultiOption($oCountry['id'], $oCountry['name']);
}
}
}
And then add it to the form this way:
class Application_Form_RegistrationForm extends Zend_Form{
public function init() {
$this->addElement(new Application_Form_Element_CountrySelect('country_id'));
}
}