I have the following model:
class Person
{
public $name;
function __Construct( $name )
{
$this->name = $name;
}
}
I have the following controller:
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', $people);
}
}
How do I get access to the model array in the view. Is there a way to access the model directly or do I have to assign a property like so:?
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
}
}
View:
<?php
foreach( $model as $person )
{
echo $person->title;
}
?>
The problem with the above will be that it can be changed by a user to
return $this->render( 'FrameworkBundle:Navigation:index.html.php', array( "marybloomingpoppin" => $people ) );
With the example view you used, you already had the correct implementation:
class NavigationController extends Controller
{
public function indexAction()
{
$people = array(
new Person("James"),
new Person("Bob")
);
return $this->render('FrameworkBundle:Navigation:index.html.php', array( "model" => $people ) );
}
}
You mentioned the concern that somebody could change the assignment in the controller, but this is something you always have if somebody changes the name of a variable only in one place and not in all. So I don't think this is an issue.
Related
I create a form like this link but when I try to submit these error shows to me
1- how to extend these form to all classes {pages} (I try it in Page & PageController and the form is repeating in my all other pages class)
2- how to fix these errors?
Page.php:
<?php
namespace {
use SilverStripe\CMS\Model\SiteTree;
use project\Subscribe;
class Page extends SiteTree
{
private static $has_many = [
'Subscribes' => Subscribe::class,
];
}
}
PageController.php:
<?php
namespace {
use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\EmailField;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\RequiredFields;
use project\Subscribe;
class PageController extends ContentController
{
private static $allowed_actions = [
'EmailForm',
];
public function EmailForm()
{
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
EmailField::create('Email',''),
),
FieldList::create(
FormAction::create('handleSubscribe','Submit')
->setUseButtonTag(true)
->addExtraClass('button')
),
RequiredFields::create('Email')
)
->addExtraClass('input-group');
foreach($form->Fields() as $field) {
$field->addExtraClass('form-control')
->setAttribute('placeholder', $field->getName().'*');
}
foreach($form->Fields() as $field) {
$field->addExtraClass('form-control')
->setAttribute('placeholder', $field->getName().'*');
}
$data = $this->getRequest()->getSession()->get("FormData.{$form->getName()}.data");
return $data ? $form->loadDataFrom($data) : $form;
}
public function handleSubscribe($data, $form)
{
$session = $this->getRequest()->getSession();
$session->set("FormData.{$form->getName()}.data", $data);
$existing = $this->Subscribes()->filter([
'Subscribe' => $data['Subscribe']
]);
if($existing->exists()) {
$form->sessionMessage('That Email already exists! Spammer!','bad');
return $this->redirectBack();
}
$subscribe = Subscribe::create();
$subscribe->PageID = $this->ID;
$form->saveInto($subscribe);
$subscribe->write();
$session->clear("FormData.{$form->getName()}.data");
$form->sessionMessage('Thanks for your comment!','good');
return $this->redirectBack();
}
}
}
Suscribe.php:
<?php
namespace projet;
use SilverStripe\ORM\DataObject;
use SilverStripe\Forms\FieldList;
class Subscribe extends DataObject
{
private static $singular_name = 'Subscribe';
private static $table_name = 'Subscribe';
private static $db = [
'Email' => 'Varchar(100)',
];
private static $has_one = [
'Page' => Page::class,
'Home' => Home::class,
];
private static $summary_fields = array(
'Email' => 'Email',
);
}
Home.php:
<?php
namespace project;
use Page;
use PageController;
class Home extends Page {
private static $singular_name = 'Home';
private static $description = 'Index Page';
private static $table_name = 'Home';
private static $icon = 'app/icon/home.png';
private static $has_many = [
'Subscribes' => Subscribe::class,
];
}
class HomeController extends PageController {
}
How to extend fix the Non-duplicate data & extends to the whole project?
I created custom actions for rest api in yii2
my codes are:
namespace app\controllers;
use yii\rest\ActiveController;
use yii\web\Response;
use Yii;
class RsController extends ActiveController{
public $modelClass='app\models\Mymodel';
/*some another actions*/
public function actionOne($id){
return \app\models\Anothermodel::findAll(['my_id'=>$id]);
}
public function actionTwo($id){
return \app\models\Anothermodel::findAll(['my_name'=>'xxxx']);
}
}
I know we can override fields function in model to get special fields but
now I wanted to get different fields for actionOne and actionTwo (of a model)
How can I override fields function in Anothermodel for this purpose?
I found my answer from here
I create a component like this
<?php
namespace app\components;
class Serializer extends \yii\rest\Serializer {
public $defaultFields;
public $defaultExpand;
public function init() {
parent::init();
$this->defaultFields = !is_null($this->defaultFields) ? implode(",", $this->defaultFields) : $this->defaultFields;
$this->defaultExpand = !is_null($this->defaultExpand) ? implode(",", $this->defaultExpand) : $this->defaultExpand;
}
protected function getRequestedFields() {
$fields = is_null($this->request->get($this->fieldsParam)) ? $this->defaultFields : $this->request->get($this->fieldsParam);
$expand = is_null($this->request->get($this->expandParam)) ? $this->defaultExpand : $this->request->get($this->expandParam);
return [
preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY),
preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY),
];
}
}
and then in my controllers action set my fields
like this.
public function actionOne($id){
$this->serializer['defaultFields'] = ["field1",
"field2"];
return new \yii\data\ActiveDataProvider([
'query' => \app\models\Anothermodel::find()->where(['my_id'=>$id]),
]);
}
public function actionTwo($id){
$this->serializer['defaultFields'] = ["field1",
"field2","field3"];
return new \yii\data\ActiveDataProvider([
'query' => \app\models\Anothermodel::find()->where(['my_id'=>$id]),
]);
}
I suggest to use events
public function actionPublic()
{
\yii\base\Event::on(Thing::class, Thing::EVENT_AFTER_FIND, function ($event) {
$event->sender->scenario = Thing::SCENARIO_SEARCH_PUBLIC;
});
return new ActiveDataProvider([
'query' => Thing::find(),
]);
}
public function actionPrivate()
{
\yii\base\Event::on(Thing::class, Thing::EVENT_AFTER_FIND, function ($event) {
$event->sender->scenario = Thing::SCENARIO_SEARCH_PRIVATE;
});
return new ActiveDataProvider([
'query' => Thing::find(),
]);
}
and inside of ActiveRecord (Thing in my case) check the scenario in fields() method
public function fields()
{
$fields = parent::fields();
if ($this->scenario === self::SCENARIO_SEARCH_PUBLIC) {
unset($fields['field1'], $fields['field2'], $fields['field3'], $fields['field4']);
}
return $fields;
}
check my answer in gihub
I'm trying to get to grips with Laravel and not finding the documentation any help at all. It seems to assume you know so much instead of actually walking new users through each section step by step.
I've got to the point where I need to make an internal call to another class, and sticking with MVC I can't seem to do what should be a simple thing.
My code:
class UsersController extends BaseController {
protected $layout = 'layouts.templates.page';
protected $messages;
public function getIndex()
{
$input = array('where', array('field' => 'email', 'operator' => '=', 'value' => 'tony#fluidstudiosltd.com'));
$request = Request::create('user/read', 'GET');
$users = json_decode(Route::dispatch($request)->getContent());
var_dump($users); exit;
$this->pageTitle = 'Fluid Customer Status :: Admin Users';
$this->content = View::make('layouts.admin.users');
}
}
Class UserController extends Base Controller
public function getRead()
{
$userId = (int) Request::segment(3);
if ($userId)
{
$user = User::findOrFail($userId);
return $user;
}
else
{
$users = new User;
var_dump(Input::all()); exit;
if (Input::has('where'))
{
var_dump(Input::get('where')); exit;
}
return $users->get();
}
}
Why isn't the input data from UsersController#getIndex available in UserController#getRead
class AppointmentsController extends AppController {
public function view($id = null) {
if (!$this->Appointment->exists($id)) {
throw new NotFoundException(__('Invalid appointment'));
}
$options = array('conditions' => array('Appointment.' . $this->Appointment->primaryKey => $id));
$this->set('appointment', $this->Appointment->find('first', $options));
$kk = $this->Appointment->find('first', array('fields' => 'status', 'conditions' => array('Appointment.id' => $id)));
$ss = reset($kk);
$stats = reset($ss);
}
}
I have set $stats via getting value from DB and i want to use in in another function in same controller
then I want to use like this
class AppointmentsController extends AppController {
function confirm(){
$stats = 'New';
}
}
Seeing that it's the same class, have you tried using $this->stats instead of a local variable?
You can call another function in your first function like
$this->confirm($status); // calling confirm function
function confirm($status)
{
//use status as you want
}
Or you can set status as global variable then this can you accessible in any function.
I think, you've to create function in the model that will return the value of the field by id.
<?php
// model/AppModel.php
public function getFieldById($field='id', $id){
return $this->field($field, array('id' => $id));
}
// in controller function you can access this like.
$status = $this->Appointment->getFieldById('status', $id); // $id will be appointment id.
?>
Having the following class that is extended by other controllers
class Admin_Controller extends Base_Controller
{
static $admin_layout = 'admin.layouts.default';
public function __construct()
{
parent::__construct();
$role_object = User::find(Auth::user()->id)->roles()->get();
$role = $role_object[0]->attributes['name'];
such as:
class Admin_Draws_Controller extends Admin_Controller
{
public $restful = true;
public function __construct()
{
$this->layout = parent::$admin_layout;
parent::__construct();
}
public function get_index()
{
$view = View::make('admin.templates.draws');
$this->layout->content = $view;
}
}
How can I send the $role variable to admin.layouts.default so I can have it when ever the view is loaded?
The point of "global" $role variable is to avoid to have to call it in all of my View::make() like the following:
$view = View::make('admin.templates.articles',
array(
'fields' => $fields,
'data' => $results,
'links' => $links,
'role' => 'role here'. // I don't want to add this where ever I call the View::make
)
);
$this->layout->content = $view;
and just do an echo $role like, in my header.blade.php
I ended up doing the following, which works.
Controller
// Example of variable to set
$this->layout->body_class = 'user-register';
$view = View::make('modules.user.register', array(
'success' => true,
));
$this->layout->content = $view;
My default.layout.php view
<body class="<?php echo isset($body_class) ? $body_class : '' ;?>">
#include('partials.header')
{{ $content }}
#include('partials.footer')
The variable, can be easily used in any other context within the view.