Assignment to a string variable in which is another variable - string

Hi i have this controler in Yii2 which render me view. Then i can write in console yii generator/generate example example and then This action generate me skeleton od model and controller which i have in my views. This is code
<?php
namespace console\controllers;
use yii\console\Controller;
class GeneratorController extends Controller {
private $viewControllerPath = "rest/modules/crm/v1/controllers/";
private $viewModelPath = 'rest/modules/crm/v1/models/';
public function actionGenerate($className, $modelClass) {
$controller = $this->renderFile('#app/views/generator/restController.php', ['className' => $className, 'modelClass' =>
$modelClass]);
file_put_contents(\Yii::getAlias($this->viewControllerPath . $className . 'Controller' . '.php'), $controller);
$model = $this->renderFile('#app/views/generator/restModel.php', ['className' => $className, 'modelClass' => $modelClass]);
file_put_contents(\Yii::getAlias($this->viewModelPath . $className . 'Model' . '.php'), $model);
}
}`
And this is this view:
`
<?php
echo "<?php\n";
?>
namespace rest\modules\<?= $modelClass ?>\v1\models;
use common\models\<?= $modelClass ?>\<?= $className ?> as CommonModel;
class <?= $className ?> extends CommonModel {
}`
The last think what i should to do is put mz variable $modelClass in this path
private $viewControllerPath = "rest/modules/crm/v1/controllers/";
instead of crm. Then my model and controler will be appear in in appropriate folders.
I try to do this but it isnt work:
private $viewControllerPath = "rest/modules/'.$modelClass.'/v1/controllers/";
Anyone can help me? Maybe i can use __constructor there but i dont know how to do it

Just replace crm word of your variables with $modelClass inside your actionGenerate function like this:
public function actionGenerate($className, $modelClass) {
// replacing 'crm' with $modelClass
if( ! empty($modelClass) ) {
$this->viewControllerPath = str_replace ( 'crm' , $modelClass , $this->viewControllerPath );
$this->viewModelPath = str_replace ( 'crm' , $modelClass , $this->viewModelPath );
}
$controller = $this->renderFile('#app/views/generator/restController.php', ['className' => $className, 'modelClass' =>
$modelClass]);
file_put_contents(\Yii::getAlias($this->viewControllerPath . $className . 'Controller' . '.php'), $controller);
$model = $this->renderFile('#app/views/generator/restModel.php', ['className' => $className, 'modelClass' => $modelClass]);
file_put_contents(\Yii::getAlias($this->viewModelPath . $className . 'Model' . '.php'), $model);
}

Related

Too few arguments to function App\Controllers\Parsys::__construct(), 0 passed in

First I code without use RequestInterface and runwell, but I when I applicate the RequestInterface from the docs here: https://codeigniter4.github.io/userguide/incoming/incomingrequest.html I got this error, What happen with my code?
<?php namespace App\Controllers;
use CodeIgniter\HTTP\RequestInterface;
class Parsys extends BaseController {
protected $request;
public function __construct(RequestInterface $request) {
$this->request = $request;
}
public function index() {
$data = [
'title' => "Parameter System",
];
return view("backend/parsys_frm", $data);
}
public function getList() {
$frm = $request->getGet('frm');
$q = $this->request->getGet('q');
$order_by = $this->request->getGet('order_by');
$page = $this->request->getGet('page');
$limit = $this->request->getGet('limit');
$limit = #$limit == 0 ? 10 : $limit;
$this->queryList($total, $current, $page, $limit, $q, [1 => 1]);
$data = $current->result_array();
header('Content-Type: application/json');
echo json_encode(compact(['total', 'page', 'limit', 'data', 'q']));
}
I use ubuntu 20.04, lampp PHP 7.4
Instead of using the __construct magic method use the built in init method.
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}

Codeigniter 4 ErrorException Undefined variable: table

I am facing this issue of Undefined variable as shown in the image attached which I am not sure what is wrong.
My code as follows:
Routes
$routes->get('account/game_reg', 'Game::index');
$routes->match(['get', 'post'], 'account/game_reg', 'Game::game_reg');
Controller
public function index()
{
$data = [];
if(!session()->get('isLoggedIn')):
return redirect()->to(base_url('account/login'));
endif;
$games = new GamelistModel();
$data['table'] = $games->getList();
echo view('templates/header', $data);
echo view('account/game_reg');
echo view('templates/footer');
}
public function game_reg()
{
$data = [];
helper(['form']);
$validation = \Config\Services::validation();
if($this->request->getMethod() == 'post'){
$user_id = session()->get('user_id');
//validations
$rules = [
'game_id' => 'required',
'ign' => 'required|is_unique[game_reg.ign]',
'acc_id' => 'required'
];
$errors = [
'ign' => [
'is_unique' => 'IGN already exist!'
],
'acc_id' => [
'is_unique' => 'Account ID already exist!'
]
];
if(!$this->validate($rules, $errors)){
$data['validation'] = $this->validator;
}else{
//store information into database
$model = new GameregModel();
$newData = [
'game_id' => $this->request->getVar('game_id'),
'ign' => $this->request->getVar('ign'),
'acc_id' => $this->request->getVar('acc_id'),
'user_id' => session()->get('user_id'),
'created_by' => session()->get('username')
];
$model->save($newData);
$session = session();
$session->setFlashdata('success', 'Game Successfully Added!');
return redirect()->to(base_url('account/game_reg'));
}
}
echo view('templates/header', $data);
echo view('account/game_reg');
echo view('templates/footer');
}
GameregModel
<?php namespace App\Models;
use CodeIgniter\Model;
class GameregModel extends Model{
protected $table = 'game_reg';
protected $allowedFields = [
'user_id',
'game_id',
'ign',
'acc_id',
'created_at',
'updated_at',
'created_by'
];
}
?>
GamelistModel
<?php namespace App\Models;
use CodeIgniter\Model;
class GamelistModel extends Model{
protected $table = 'game_list';
protected $primarykey = 'game_id';
protected $allowedFields = [
'game_id',
'game_name'
];
public function getList()
{
return $this->orderBy('game_id', 'ASC')->findAll();
}
}
?>
Views
<select id="myDropdown">
<?php
$i = 1;
foreach($table as $t) :
$i++;
?>
<option value="<?= $t['game_id']; ?>" data-imagesrc="/img/logo_<?= strtolower($t['game_name']); ?>.jpg"><?= $t['game_name']; ?></option>
<?php endforeach; ?>
</select>
If I remove away the is_unique function, everything works perfectly fine but when I include the is_unique, I get the error. What I am trying to do is, I would retrieve a list of games updated by admin, user will then choose from this list and save into their profile.
Hope someone can help me out of this.
Thanks in advance guys!
You are only sending the data into one of your views. The one using the $table variable does not have access to it.
So in your loading views code you have to do the following:
echo view('templates/header', $data);
echo view('account/game_reg', $data);
echo view('templates/footer', $data);
It's better to just send the data across all views.
The other thing I noticed (nothing to do with the problem here) is that you're closing the php tags inside your models. Never do that. Your classes should never have the php closing tag ?>.

How to use Aliasing Helpers in cakephp 3?

I need to modify Html->link to check acl before generate a link. Then I use aliasing helper to do this. I have in appController
public $helpers = ['Tools' , 'Html' => ['className' => 'Mhtml']];
And in src/View/Helper/MhtmlHelper.php I have
<?php
namespace App\View\Helper;
use Cake\View\Helper;
use Cake\View\Helper\HtmlHelper;
class MhtmlHelper extends HtmlHelper {
public function acl() {
//return true if it is able to verify the user’s access, else false
}
public function link($title , $url=null , $options=[]) {
return $this->acl ? parent::link($title , $url , $options) : '';
}
}
But I run into this error
Strict (2048): Declaration of App\View\Helper\MhtmlHelper::link() should be compatible with Cake\View\Helper\HtmlHelper::link($title, $url = NULL, array $options = Array) [APP/View\Helper\MhtmlHelper.php, line 6]
What is wrong?
You need to declare the link function like this:
public function link($title , $url = null , array $options = []) {
return $this->acl ? parent::link($title , $url , $options) : '';
}

Yii search method get don't work and don't compare with data in database

Hi yesterday i tried one way to create search by datetime, and you can see link: Search task on the next post.
Today I try one another way: When I succed i will put sollution back thank you.
This is my search file:
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php
/* #var $this ApplicationController */
/* #var $model Application */
/* #var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
'enableAjaxValidation'=>false,
//$model->search(),
)); ?>
<div class="row">
<?php echo $form->label($model,'AUUsername'); ?>
<?php echo $form->textField($model,'AUUsername',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php
//datepicker for date_from
echo CHtml::label("From date", 'datepicker');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name' => 'filters[date_from]',
//'value' => $filters['date_from'],
// additional javascript options for the date picker plugin
'options' => array(
'showButtonPanel' => true,
'showAnim' => 'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat'=>'yyyy-mm-dd hh:mm:ss',
),
'htmlOptions' => array(
'id'=>'date_from',
),
));?>
</div>
<div class="row">
<?php
//datepicker for date to
echo CHtml::label("To date", 'datepicker');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name' => 'filters[date_to]',
//'value' => $filters['date_to'],
// additional javascript options for the date picker plugin
'options' => array(
'showButtonPanel' => true,
'showAnim' => 'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat'=>'yyyy-mm-dd hh:mm:ss',
),
'htmlOptions' => array(
'id'=>'date_to',
),
));?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
This is my model file:
<?php
class AppLog extends AltActiveRecord
{
private $_ActionName=null;
public $date_from;
public $date_to;
public function getDbConnection(){
return Yii::app()->connectionManager->getConnection(Yii::app()->user->getState('application'));
}
public function relations ()
{
return array (
'actions'=>array(self::HAS_ONE, 'Actions', array('ActionID'=>'ActionID')),
);
}
public function getActionName()
{
if ($this->_ActionName === null && $this->actions !== null)
{
$this->_ActionName = $this->actions->ActionName;
}
return $this->_ActionName;
}
public function setActionName($value)
{
$this->_ActionName = $value;
}
public function tableName()
{
return 'applog';
}
public function rules()
{
return array(
array('AppUserID','length', 'max'=>11),
array('AUUsername','length', 'max'=>45),
array('AUActionTime','type','type'=>'datetime','datetimeFormat'=>'yyyy-mm-dd hh:mm:ss'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('AppUserID,AUUsername, date_from, date_to', 'safe', 'on'=>'search'),
);
}
public function attributeLabels()
{
return array(
'ActionID' => 'ID',
'AUUsername' => 'Naziv korisnika',
'AUActionTime' => 'Vrijeme akcije',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('APUsername',$this->AUUsername,true);
$criteria->compare('AUActionTime',$this->AUActionTime,true);
$criteria->compare('date_from',$this->date_from,true);
$criteria->compare('date_to',$this->date_to,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
?>
THIS IS MY CONTROLLER ACTION FOR SEARCH
public function actionLista()
{
$model = new Datalist;
$this->layout='column1';
//
if($_GET!=null)
{
$date_from = $_GET['filters']['date_from'];
$params[':date_from'] = date('yyyy-mm-dd hh:mm:ss', strtotime($_GET['filters']['date_from']));
$date_to = $_GET['filters']['date_to'];
$params[':date_to'] = date('yyyy-mm-dd hh:mm:ss', strtotime($_GET['filters']['date_to']));
if($date_from == '') $params[':date_from'] = date('yyyy-mm-dd hh:mm:ss', strtotime('2014-01-01 00:00:00'));
if($date_to == '') $params[':date_to'] = date('yyyy-mm-dd hh:mm:ss', strtotime('2999-01-01 00:00:00'));
//$condition = '(AUActionTime>:date_from OR AUActionTime<:date_to)';
//set filters
//$this->setFilters($_GET['filters']);
//die(CVarDumper::dump($params,10,true));
}
else {
$this->filters = array(
'date_from' => date('yyyy-mm-dd hh:mm:ss', strtotime('2014-01-01')),
'date_to' => date('yyyy-mm-dd hh:mm:ss', strtotime('today + 1 day')),
);
}
1) In your controller you should set the scenario as "search" like this
$model = new Datalist('search');
$model->unSetAttributes();
2) You need to assign the $_GET values to the model before view is rendered like this
// If your get vars are different then accordingly
if(isset($_GET['AppLog'])){
$model->attributes = $_GET['AppLog'];
....
$model->date_to = $date_to // After you retrieved and formatted from $_GET as above
$model->date_from = $date_from
Your controller action does not seem to rendering a view; i am assuming that you have omitted it here, but you are displaying the output in someway

zend : Fatal error: Class 'Application_Model_User' not found

I am trying connecting to my model class defined in /application/models named user.php.
Following is how my Bootstrap looks like:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap{
protected function _initAppAutoload() {
$autoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => 'Application',
'basePath' => APPLICATION_PATH,
'resourceTypes' => array(
'model' => array(
'path' => 'models',
'namespace' => 'Model',
)
)
));
echo '<pre>';
var_dump($autoloader);
return $autoloader;
}
}
Folling is my application.ini
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
Following is my IndexController.php
class IndexController extends Zend_Controller_Action {
private $user_connection;
private $login_status;
public function init() {
/* Initialize action controller here */
$this->user_connection = new Application_Model_User();
}
public function indexAction() {
$sql = " SELECT *
FROM USER";
$this->view->deals = $this->user_connection->select($sql);
}
following is my user.php file:
class Application_Model_User extends Application_Model_Db_Connection {
public function __construct() {
parent::__construct();
}
public function Connection(){
return $this->getConnection();
}
public function insert($data, $table = 'user'){
return parent::insert($table, $data);
}
public function select($sql){
return parent::select($sql);
}
}
Strange part is, I am developing on windows and everything runs fine, but when I push the same code to my ec2 linux instance, I get this fatal error.
Fatal error: Class 'Application_Model_User' not found in /var/www/html/dev/application/controllers/IndexController.php on line 11
I went through many questions on stack overflow and tried most of them, but I am not close to solve this problem. Any help would be appreciated.
I was able to fix the above issue, it was due to case sensitivity of linux. I renamed my models with first letter capital and was able to access them in my Controller.
user.php -> User.php
also for adding subfolder to your model you can add following to the bootstrap.
protected function _initAppAutoload() {
$autoloader = new Zend_Loader_Autoloader_Resource(array(
'namespace' => 'Application',
'basePath' => APPLICATION_PATH,
'resourceTypes' => array(
'model' => array(
'path' => 'models/',
'namespace' => 'Model_',
),
'model_db' => array(
'path' => 'models/db',
'namespace' => 'Model_Db_'
)
)
));

Resources