How to point to a different Controller of a Model in CakePHP - php

I have one Model class named 'Name' and one Controller class named 'Controller1'. I have created a form using 'Name' model which is by default pointing to 'names' controller as per default naming convention of cakephp. But i want it to point to 'Controller1' controller..
I've replace this code:-
<?php echo $this->Form->create('Name'); ?>
with this one to see if it works:-
<?php
echo $this->Form->create('Name',array('controller'=>'Controller1',
'action'=>'view'));
?>
But it is not working and is pointing to 'names' controller only.
How can i point it to 'Controller1' instead of 'names' controller?
More details:-
Model (Name.php):-
class Name extends AppModel{
public $useTable = "tbl_names";
}
Controller (Controller1Controller.php):-
class Controller1Controller extends AppController
{
public function index(){
}
public function view($id){
$name ='';
if($this->request->is('post')){
$name = $this->request->data('name');
if($name==="xyz"){
$this->redirect('http://www.google.com');
}else{
$this->Save($this->request->data);
$this->request->data['name']= 'Nice';
}
}
return $id;
}
// Save to database if entered name is other than 'xyz'
private function Save($data){
$this->Name->create();
}
public function viewname($id,$name){
}
}

You have to set url key to pass crontroller and action values.
echo $this->Form->create(false, array(
'url' => array('controller' => 'recipes', 'action' => 'add'),
'id' => 'RecipesAdd'
));
See FormHelper > Options for create()

Related

Call to a member function selectID() on null (Concrete CMS 8.5.7)

I need a new form select to allow me to set a different id and name in a select form. So I am trying to extend the form class. I did the following.
concrete\packages\concrete_form_addon\src\Concrete\Form\Service\Form2.php
namespace Concrete\Package\ConcreteFormAddon\Form\Service;
class Form2 extends \Concrete\Core\Form\Service\Form {
public function selectID($key, $optionValues, $valueOrMiscFields = '', $miscFields = []) {
working code for the option
}
}
Then in the class file I have
namespace Concrete\Package\ConcreteFormAddon;
use Concrete\Core\Asset\Asset;
use Concrete\Core\Asset\AssetList;
use Concrete\Core\Package\Package;
use Concrete\Core\Page\Page;
use Concrete\Core\Support\Facade\Route;
use Concrete\Core\Support\Facade\Config;
use Whoops\Exception\ErrorException;
class Controller extends Package {
protected $pkgHandle = 'concrete_form_addon';
protected $appVersionRequired = '8.4';
protected $pkgVersion = '0.8.7';
protected $pkgAutoloaderRegistries = [
'src/Concrete/Form' => 'Concrete\Package\ConcreteFormAddon\Form',
];
public function getPackageDescription() {
return 'Add custom form functions to Concrete CMS';
}
public function getPackageName() {
return 'Concrete Form Add-On';
}
}
Then the line of code that calls it:
<?= $form2->selectID('', $manufacturers, $product->getManufacturer() ? $product->getManufacturer()->getID() : '', ['id' => 'pManufacturer' . $pID, 'name' => 'pManufacturer[]', 'class' => 'selectize pricing-fields']) ?>
If I put the first bit of code in the core file it works fine if I use $form->selectID so there is something wrong with the way I'm setting up the class I believe.

CakePHP: How to use a non-default user model for authentication?

Hi i have a table name chat_users
I have connected users table for last few projects it working fine. But this is my first project i have a different table name chat_users
I want to login this table with username and password
I have tried but unable to login.
Please help me.
Code-
AppController.php
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array('Auth', 'Session', 'Email', 'Cookie', 'RequestHandler', 'Custom');
public $helpers = array('Html', 'Form', 'Cache', 'Session','Custom');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'fields' => array('ChatUser.username' => 'username', 'ChatUser.password' => 'password'),
)
);
}
}
?>
UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $name = 'Users'; //Controller name
public $uses = array('ChatUser');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login');
}
public function index() {
}
public function login() {
$this->layout='login';
if ($this->request->is('post')) {
if (!$this->Auth->login()) {
$this->Session->setFlash(__('Invalid username or password, try again'), 'error_message');
$this->redirect($this->Auth->redirect());
}
}
if ($this->Session->read('Auth.ChatUser')) {
return $this->redirect(array('action' => 'index'));
exit;
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
Above query i am getting missing table.
See screenshot-
Your auth component configuration is incorrect. You are missing the appropriate userModel option, which defines the name of the model to use
And the fields configuration doesn't work the way your are using it, the keys must be named username and password, and the value can then contain the actual column name, however since your columns are obviously using the default names, there's no need to use this option at all.
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'userModel' => 'ChatUser'
)
);
Also the session key will always be Auth.User unless you are explicitly changing it via AuthComponent::$sessionKey:
$this->Auth->sessionKey = 'Auth.ChatUser';
However, you are better of using the auth component to access the user data anyways:
// Use anywhere
AuthComponent::user('id')
// From inside a controller
$this->Auth->user('id');
See also
Cookbook > Authentication > Configuring Authentication handlers
Cookbook > Authentication > Accessing the logged in user

Getting module's name from model's name

I need to know a module name for a particular model, if I know only model's name.
For example, I have:
model Branch, stored in protected/modules/office/models/branch.php and
model BranchType stored in protected/modules/config/models/branchtype.php.
I want to know the module name of branch.php from the class of branchtype.php.
How to do this?
Unfortunately Yii does not provide any native method to determine the module name that model belongs to. You have to write your own algorithm to do this task.
I can suppose you two possible methods:
Store configuration for module's models in the module class.
Provide the name of your model using path aliases
First method:
MyModule.php:
class MyModule extends CWebModule
{
public $branchType = 'someType';
}
Branch.php
class Branch extends CActiveRecord
{
public function init() // Or somewhere else
{
$this->type = Yii::app()->getModule('my')->branchType;
}
}
In configuration:
'modules' =>
'my' => array(
'branchType' => 'otherType',
)
Second method:
In configuration:
'components' => array(
'modelConfigurator' => array(
'models' => array(
'my.models.Branch' => array(
'type' => 'someBranch'
),
),
),
)
You should write component ModelConfigurator that will store this configuration or maybe parse it in some way. Then you can do something like this:
BaseModel.php:
class BaseModel extends CActiveRecord
{
public $modelAlias;
public function init()
{
Yii::app()->modelConfigurator->configure($this, $this->modelAlias);
}
}
Branch.php:
class Branch extends BaseModel
{
public $modelAlias = 'my.models.Branch';
// Other code
}
Try this:
Yii::app()->controller->module->id.
Or inside a controller:
$this->module->id
in Yii2 try this:
echo Yii::$app->controller->module->id;
for more information see Get the current controller name, action, module

validation is always true in cakephp

Im new to cakePHP and tried to create a simple user registration. Now I'm stuck since two days in the validation of the form. The validation function returns always true and so the form is always saved to the database, even if it is empty.
So here are the model, the controller and the view. Maybe you can see what I did wrong here?
/app/Model/MemberModel.php
<?php
class Member extends AppModel {
var $validate = array(
"username" => array(
"rule" => "alphaNumeric",
"allowEmpty" => false
)
);
}
?>
/app/Controller/MemberController.php
<?php
class MemberController extends AppController {
var $components = array("Security");
var $helpers = array("Html", "Form");
public function index() {
}
public function register() {
if($this->request->is("post")) {
Security::setHash("blowfish");
$this->Member->set($this->request->data);
debug($this->Member->validates());
if($this->Member->save(array("password" => Security::hash($this->request->data["Member"]["password"])))) {
$this->Session->setFlash(__("Saved."));
} else {
$this->Session->setFlash(__("Error: ").$this->validationErrors);
}
}
}
}
?>
/app/View/Member/register.ctp
<?php
echo $this->Form->create("Member");
echo $this->Form->input("username");
echo $this->Form->input("password");
echo $this->Form->end("Register");
?>
Oh, I just realized your problem.
/app/Model/MemberModel.php
should be
/app/Model/Member.php
The controller will look for Member.php, and if it can't find it, it will try the default $validate behavior in AppModel

Yii CActiveDataProvider with class argument?

I found this code at this website. What would have to be in the $dp dataprovider for the class TotalColumn to be called in the CGridView? Do I have to have the class TotalColumn be somewhere in $dp? Any idea how I would declare that CActiveDataProvider?
<?php
// protected/views/inventory/index.php
Yii::import('zii.widgets.grid.CGridColumn');
class TotalColumn extends CGridColumn {
private $_total = 0;
public function renderDataCellContent($row, $data) { // $row number is ignored
$this->_total += $data->quantity;
echo $this->_total;
}
}
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $dp, // provided by the controller
'columns' => array(
'id',
'name',
'quantity',
array(
'header' => 'Total',
'class' => 'TotalColumn'
)
)));
Here is my code, but nothing in my custom column is displayed:
Yii::import('zii.widgets.grid.CGridColumn');
class TotalSkills extends CGridColumn
{
private $test = "blah";
public function renderSkills($row, $data)
{
echo $this->test;
}
}
// People
echo CHtml::label('People', 'yw0', $shared_html_options);
$dataProvider = new CActiveDataProvider('Person');
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'name',
'age',
array(
'header'=>'Total Skills',
'class'=>'TotalSkills'
)
)
));
You should create the TotalColumn class inside your protected/components directory as a TotalColumn.php file. That way you can use it in many different view files, instead of the view file that is defined only. Yii will load it automatically then.
$dp should be a typical DataProvider class (more likely a CActiveDataProvider) that is defined in your controller and passed to your view. The DataProvider can be as easy as the CGridView documentation describes it.
public function renderDataCellContent($row, $data)
is defined method in gridview
but there is no method such as
public function renderSkills($row, $data)
in gridview

Categories