Codeigniter 4 ErrorException Undefined variable: table - codeigniter-4

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 ?>.

Related

Shopware: Store custom field for customer

I added this custom field to my customer and to the register form in storefront/component/account/register.html.twig:
<input type="checkbox" class="custom-control-input" id="alumni" name="custom_kw_dau" value="1">
The field is type checkbox. It works fine in the backend but it is not filled during customer registration.
You have to manually store it. Subscribe to event and add the field to customFields in the output like this:
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::MAPPING_REGISTER_CUSTOMER => 'addCustomField'
];
}
public function addCustomField(DataMappingEvent $event): bool
{
$inputData = $event->getInput();
$outputData = $event->getOutput();
$custom_field = (bool)$inputData->get('custom_kw_dau', false);
$outputData['customFields'] = array('custom_kw_dau' => $custom_field);
$event->setOutput($outputData);
return true;
}
Yeah you need to subscribe to the event - but I have done it like this instead of the above event, and it works fine as well.
public static function getSubscribedEvents(): array
{
return [
CustomerRegisterEvent::class => 'onRegister',
GuestCustomerRegisterEvent::class => 'onRegister'
];
}
public function onRegister(CustomerRegisterEvent $event): void
{
$request = $this->requestStack->getCurrentRequest();
if ($request) {
$params = $request->request->all();
$customer = $event->getCustomer();
$data = [
'id' => $customer->getId(),
'customFields' => [
'your_field' => $params['your_field']
]
];
$this->customerRepository->update([$data], $event->getContext());
}
}
But I think the answer above might be more suitable as it does not require any additional services.

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 BadMethodCallException

I am trying to do a user login and I am getting this error which I can't figure out why. Also, I am not sure whether I can mentioned 1 more question or do I have to separate it on another topic. If I want user to login using either username or email address, how should I do it?
I have uploaded the error message here
The error seems to be at this line :
$user = $model->model('username', $this->request->getVar('username'))
->first();
Below are my code:
Controller
public function login()
{
$data = [];
helper(['form']);
$validation = \Config\Services::validation();
if($this->request->getMethod() == 'post'){
//validations
$rules = [
'username' => 'required',
'password' => 'required|validateUser[username, password]'
];
$errors = [
'password' => [
'validateUser' => 'Username or Password don\'t match'
]
];
if(!$this->validate($rules, $errors)){
$data['validation'] = $this->validator;
}else{
$model = new AccountModel();
$user = $model->model('username', $this->request->getVar('username'))
->first();
$this->setUserMethod($user);
return redirect()->to('account');
}
}
echo view('templates/header', $data);
echo view('account/login');
echo view('templates/footer');
}
Model
<?php namespace App\Models;
use CodeIgniter\Model;
class AccountModel extends Model{
protected $table = 'users';
protected $allowedFields = [
'username',
'email',
'firstname',
'lastname',
'dob',
'country',
'contact',
'password',
'created_at',
'updated_at',
'created_by'
];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
protected function beforeInsert(array $data) {
$data = $this->passwordHash($data);
return $data;
}
protected function beforeUpdate(array $data) {
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data){
if(isset($data['data']['password']))
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
return $data;
}
}
?>
Hope someone can help me out here. Thanks in advance!
So you have this line trying to call a method called model which does not exist...
This is what you have...
$user = $model->model('username', $this->request->getVar('username'))
->first();
If you have read the CodeIgniter User Guide, you would see that you really want to be using where instead of model... Maybe cause you had model stuck in your head, as that happens sometimes.
$user = $model->where('username', $this->request->getVar('username'))->first();
See how that flies for you.

Always the same view content on slim framework with twig after save changes

I'm using Slim and Twig and I'm trying to change a view content, but it doesn't change after I saved the changes.
This is the controller:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../../vendor/autoload.php';
require './classes/connection.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../../views', [
'cache' => '../../views_cache'
]);
// Instantiate and add Slim specific extension
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
/*$name = $args['name'];
$response->getBody()->write("Hello, $name");
echo getcwd();
return $response;*/
return $this->view->render($response, 'login.html', [
'name' => $args['name']
]);
});
$app->post('/login', function (Request $request, Response $response, array $args) {
$post_data = $request->getParsedBody();
if (isset($post_data['user']) && isset($post_data['pass'])) {
$mongo = new Connection();
$conn = $mongo->getConnection();
$collection = $conn->prueba->users;
$result = $collection->find(['user' => $post_data['user']])->toArray();
$dbUser = $result[0]['username'];
$dbPass = $result[0]['password'];
if (password_verify($post_data['pass'], $dbPass)) {
echo '¡La contraseña es válida!';
} else {
echo 'La contraseña no es válida.';
}
} else {
return $response->withJson(array('login_status' => 'ko'));
}
});
$app->run();
What I missed to see the view changes? I think it's something about compile view but I'm not sure. It's the first time I use this framework.

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

Resources