yii2 blank page issue in all crud create and update actions - yii2-basic-app

Please help me.
I have problem as follow:
At the localhost everything ok.
But, at hosting after model save method, controller redirect method return blank page without any error.
my code here:
public function actionCreate()
{
$model = new Project();
$file = UploadedFile::getInstance($model, 'file');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if($file) {
$path = 'uploads/projects/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$model->image = $path;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
But redirect method works normally outside model save() method.
Thanks

Try this.
Edited:
public function actionCreate()
{
$model = new Project();
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
if($file) {
$path = 'uploads/projects/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$model->image = $path;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

Related

Codeigniter 4 Rest API - 301 Moved Permanently

I have Codeigniter 4 web app that run REST API with firebase/php-jwt on Laragon 5.0.0210523 environment that run Apache-2.4.47, PHP-8.1.7, and MongoDB-4.0.28. I followed a tutorial and it works fine both server REST API and it REST client. After day work, i stop laragon server. In the next day i try run REST API server then tried then run the client but it failed and gave 301 moved permanently error, but i still can access it from postman.
REST API server side
composer.json
***
"require": {
"php": "^7.4 || ^8.0",
"codeigniter4/framework": "^4.0",
"mongodb/mongodb": "^1.12",
"firebase/php-jwt": "^6.3"
},
***
.env file
***
JWT_SECRET_KEY = SomeThing$089
JWT_TIME_TO_LIVE = 3600
app.baseURL = 'http://ci4-api.localhost'
***
Route.php
***
$routes->get('/', 'Home::index');
$routes->resource('api/users');
$routes->post('api/auth', [\App\Controllers\Api\Auth::class, 'index']);
***
JWT_Helper.php
use App\Models\ModelUsers;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
/**
* #throws Exception
*/
function getJWT($authHeader)
{
if (is_null($authHeader)){
throw new Exception("Authentication JWT failed");
}
return explode(" ", $authHeader)[1];
}
function validateJWT($encodedToken)
{
$key = getenv('JWT_SECRET_KEY');
$decodedToken = JWT::decode($encodedToken, new Key($key, 'HS256'));
$modelUsers = new ModelUsers();
$modelUsers->get_email($decodedToken->email);
}
function createJWT($email): string
{
$timeRequest = time();
$timeToken = getenv('JWT_TIME_TO_LIVE');
$timeExpired = $timeRequest + $timeToken;
$payload = [
'email' => $email,
'iat' => $timeRequest,
'exp' => $timeExpired,
];
return JWT::encode($payload, getenv('JWT_SECRET_KEY'), 'HS256');
}
FilterJWT.php
namespace App\Filters;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Exception;
class FilterJWT implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request, $arguments = null)
{
$header = $request->getServer('HTTP_AUTHORIZATION');
try {
helper('jwt');
$encodedToken = getJWT($header);
validateJWT($encodedToken);
return $request;
} catch (Exception $ex) {
return Services::response()->setJSON(
[
'error' => $ex->getMessage(),
]
)->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// TODO: Implement after() method.
}
}
Filters.php
***
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'auth' => FilterJWT::class,
];
public $filters = [
'auth' => [
'before' => [
'api/users/*',
'api/users'
]
]
];
***
ModelUsers.php
namespace App\Models;
use App\Libraries\MongoDb;
class ModelUsers
{
private $database = 'ci4_api';
private $collection = 'user';
private $conn;
function __construct()
{
$mongodb = new MongoDb();
$this->conn = $mongodb->getConn();
}
function get_user_list() {
try {
$filter = [];
$query = new \MongoDB\Driver\Query($filter);
$result = $this->conn->executeQuery($this->database. '.' . $this->collection, $query);
return $result->toArray();
} catch (\MongoDB\Driver\Exception\RuntimeException $ex) {
show_error('Error while fetching users: ' . $ex->getMessage(), 500);
}
}
***
Auth.php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Models\ModelUsers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Validation\Validation;
use Config\Services;
class Auth extends BaseController
{
use ResponseTrait;
private ModelUsers $model;
private Validation $validation;
function __construct()
{
$this->model = new ModelUsers();
$this->validation = Services::validation();
}
public function index()
{
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$data1 = [
'email' => $email,
'password' => $password
];
if (!$this->validation->run($data1, 'login')) {
$errors = $this->validation->getErrors();
$response = [
'status' => 201,
'error' => null,
'messages' => [
'errors' => [
$errors
]
],
];
return $this->respond($response);
}
$data1 = $this->model->get_email($email);
//return $this->respond($data1, 200);
if (!$data1) {
$response = [
'status' => 201,
'error' => null,
'messages' => [
'error' => 'Data user atau password tidak ada1'
],
];
return $this->respond($response, 200);
}
$password_user = $data1->password;
if (password_verify($password_hash, $password_user) != 0){
$response = [
'status' => 201,
'error' => null,
'messages' => [
'error' => 'Data user atau password tidak ada2'
],
];
return $this->respond($response, 200);
}
helper('jwt');
$response = [
'message' => 'Auth berhasil dilakukan',
'data' => $data1,
'access_token' => createJWT($email)
];
return $this->respond($response, 200);
}
***
users.php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Models\ModelUsers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\Response;
use CodeIgniter\Validation\Validation;
use Config\Services;
class Users extends BaseController
{
use ResponseTrait;
private ModelUsers $model;
private Validation $validation;
function __construct()
{
$this->model = new ModelUsers();
$this->validation = Services::validation();
}
public function index(): Response
{
$data = $this->model->get_user_list();
$count = count($data);
if ($count <= 0) {
$data = [
'status' => 201,
'error' => null,
'message' => [
'success' => 'Tidak ada data daftar pegawai'
],
];
}
return $this->respond($data, 200);
}
***
REST Client
.env file
***
app.baseURL = 'http://ci4-test.localhost'
***
Routes.php
***
$routes->get('/rest', [\App\Controllers\Rest\RestClient::class, 'index']);
***
RestClient.php
namespace App\Controllers\Rest;
use App\Controllers\BaseController;
use Config\Services;
class RestClient extends BaseController
{
public function index()
{
$client = Services::curlrequest();
$token = "someToken";
$url = "http://ci4-api.localhost/api/users/";
$headers = [
'Authorization' => 'Bearer ' . $token,
];
$response = $client->request('GET', $url, ['headers' => $headers, 'http_errors' => false]);
return $response->getBody();
}
}
Postman
api auth
api all user list
I have already tried some simple solution, like reload all laragon service like apache server and mongodb, restart the windows and tried find online, but it only suggest that the url is incorectly used like in this one []https://stackoverflow.com/questions/56700991/codeigniter-301-moved-permanently[3]
Is there anyone have same issue or solution, thanks in advance.
After trying some few more time, i found the problem. It still around about url similiar like in case of Codeigniter 301 Moved Permanently, but my problem i added "/" on my url.
eg
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users/";
Maybe i added it after copy paste process
so the correct url is
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users";
hopefully help some people facing same problem

how to convert the pure soap php to laravel 5

I am new in laravel 5. This code is ok in pure php. But I don't know how to convert this to laravel 5. Can you tell me how to transfer this code to laravel 5.
client.php:
<?php class client {
public function __construct()
{
$params = array('location' => 'http://localhost:8888/csoap/server.php',
'uri' => 'urn://localhost:8888/csoap/server.php');
/* Initialize webservice */
$this->instance = new SoapClient(NULL, $params);
}
public function getString($id)
{
return $this->instance->__soapCall('getOutputString', $id);
}
}
$client = new client();
$id = array('id' => '1');
echo $client->getString($id);
?>
csoap/server.php:
<?php class server {
public function getOutputString($id)
{
$str = 'Youre ID is ' . $id . '.';
return $str;
}
}
$params = array('uri' => 'http://localhost:8888/csoap/server.php');
$server = new SoapServer(NULL, $params);
$server->setClass('server');
$server->handle();
?>
This is how I performed my installation in laravel 5.1
"require": {
"artisaninweb/laravel-soap": "0.2.*"
}
run: composer install or composer update
Add the service in config/app.php.
'providers' => [
...
...
Artisaninweb\SoapWrapper\ServiceProvider',
]
'aliases' => [
...
...
'SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper'
]
This is my client soap:
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class DataSoap {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('mydata')
->wsdl('http://localhost:8888/csoap/Server.php')
->trace(true)
});
$data = [
'str' => 'Hello World',
];
// Using the added service
SoapWrapper::service('mydata', function ($service) use ($data) {
var_dump($service->getFunctions());
var_dump($service->call('getString', [$data])->getSringResult);
});
}
}
When I run the this code, I get an error
Class 'Artisaninweb\SoapWrapper\ServiceProvider' not found
You should change:
Artisaninweb\SoapWrapper\ServiceProvider
to:
Artisaninweb\SoapWrapper\ServiceProvider::class
and also:
SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper
to:
SoapWrapper' => Artisaninweb\SoapWrapper\Facades\SoapWrapper::class

Redirect while error in form ZF2

I have a ZF2 form and validators.
I located at http://example.com/public/questions/edit/5730/2770,
where 5730 - $_GET['variant_id'], 2770 - $_GET['test_id'].
When I set input to empty value and submit form - I have an error, and ZF2 redirect me to http://example.com/public/questions/edit/5730 - without test_id (/2770).
How I can redirect me to a valid url? Thank all for answers.
Action:
public function editAction()
{
$language = 'EN';
$request = $this->getRequest();
$this->layout()->setVariable('messenger', 'Edit Questions');
$id = $this->params()->fromRoute('id');
$variantId = $this->params()->fromRoute('variant_id');
$sm = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$stCategories = new CategoriesTable($sm);
$conFunc = new FunctionsController();
$form = new Form\AddQuestionsForm();
$stCVariants = new ContestVariantsTable($sm);
$stQuestions = new QuestionsTable($sm);
$categoryList = $stCategories->getCategories($language);
$categories = $conFunc->_getSubs(null, $categoryList);
$config = $this->getServiceLocator()->get('config');
$folder = $config['settings']['url'] . $config['settings']['media_files'];
if (empty($id) && !$request->isPost()) {
$this->redirect()->toRoute('stickynotes', array('controller' => 'stickynotes', 'action' => 'contests'));
} elseif ($request->isPost()) {
$form->setInputFilter($stQuestions->getAddQuestionsFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$arrPost = (array) $request->getPost();
$arrFile = (array) $request->getFiles();
$postData = array_merge_recursive($arrPost, $arrFile);
$tryAddQuestion = $stQuestions->updateQuestions($postData);
if ($tryAddQuestion['query'] && $tryAddQuestion['exception'] === null) {
$isUpload = new \Zend\Validator\File\UploadFile();
if ($isUpload->isValid($postData['filebutton'])) {
$path_parts = pathinfo($postData['filebutton']['name']);
$extension = '.' . $path_parts['extension'];
$filename = $tryAddQuestion['lastId'];
$config = $this->getServiceLocator()->get('config');
$folder = $config['settings']['media_files'];
if ($postData['AddQuestionMedia'] == 'image') {
$validator = new \Zend\Validator\File\IsImage();
$validator2 = new \Zend\Validator\File\Extension(array('png', 'jpeg', 'jpg', 'gif'));
if ($validator->isValid($postData['filebutton'])
&& $validator2->isValid($postData['filebutton'])) {
$filter = new \Zend\Filter\File\Rename($folder . 'images/' . $filename . $extension);
$filter->filter($postData['filebutton']);
chmod($config['settings']['media_files'] . 'images/' . $filename . $extension, 0644);
$stQuestions->updateQuestionsFile($filename, $extension);
}
} elseif ($postData['AddQuestionMedia'] == 'video') {
$validator = new \Zend\Validator\File\Extension(array('mp4'));
if ($validator->isValid($postData['filebutton'])) {
$filter = new \Zend\Filter\File\Rename($folder . 'videos/' . $filename . '.mp4');
$filter->filter($postData['filebutton']);
chmod($config['settings']['media_files'] . 'videos/' . $filename . '.mp4', 0644);
$stQuestions->updateQuestionsFile($filename, $extension);
}
} elseif ($postData['AddQuestionMedia'] == 'audio') {
$validator = new \Zend\Validator\File\Extension(array('mp3'));
if ($validator->isValid($postData['filebutton'])) {
$filter = new \Zend\Filter\File\Rename($folder . 'sounds/' . $filename . '.mp3');
$filter->filter($postData['filebutton']);
chmod($config['settings']['media_files'] . 'sounds/' . $filename . '.mp3', 0644);
$stQuestions->updateQuestionsFile($filename, $extension);
}
} else {
$this->layout()->setVariable('messenger_error', 'Uploaded file have incorrect format');
}
}
$this->layout()->setVariable('messenger_info', 'Question has been updated!');
$this->redirect()->toRoute('questions', array('controller' => 'questions', 'action' => 'edit',
'id' => $id, 'variant_id' => $postData['question_id']));
} elseif(!empty($tryAddContest['exception'])) {
$this->layout()->setVariable('messenger_error', 'Failed with DB while update question. Please try again. ' . $tryAddQuestion['exception']);
} else {
$this->layout()->setVariable('messenger_error', 'Failed while update question. Please try again.');
}
if (!empty($postData['variant_id'])) {
$stCVariants->addEntity($postData['variant_id'], $tryAddQuestion['lastId']);
}
}
} else {
if (!empty($variantId)) {
$getContest = $stCVariants->getSingleContest($variantId);
$progressions = array();
$used_progressions = $stCVariants->getUsedProgressions($id);
for ($i=$getContest['progression_start']; $i<=$getContest['progression_stop']; $i++) {
if (!in_array($i, $used_progressions))
$progressions[] = $i;
}
$form->remove('AddQuestionProgression');
$form->getInputFilter()->remove('AddQuestionProgression');
$select = new \Zend\Form\Element\Select('AddQuestionProgression');
$select->setValueOptions($progressions)->setAttributes(array(
'id' => 'progression_id',
'class' => 'form-control',
'style' => 'width: 408px;',
));
$form->get('variant_id')->setValue($id);
$form->add($select);
}
$getQuestion = $stQuestions->getSingleQuestion($id);
switch ($getQuestion['media_type']) {
case 'image':
$folder .= 'images/' . $getQuestion['media_content'];
break;
case 'video':
$folder .= 'videos/' . $getQuestion['media_content'];
break;
case 'audio':
$folder .= 'sounds/' . $getQuestion['media_content'];
break;
}
$form->get('variant_id')->setValue($id);
$form->get('question_id')->setValue($variantId);
}
return array(
'form' => $form,
'categories' => $categories,
'url' => $folder,
'id' => $id
);
}

Zend skeleton application Class 'Album\Model\AlbumTable' not found

I'm trying to figure out what's wrong with my first tutorial using Zend Skeleton App. I'm using Zend Studio 10 + ZendServer and Zf2.2; managed to get the skeleton app working and now got stuck on a missing class problem (see error below). I have tried various approaches but the result is the same: it's not working. Here are my files, any help would be appreciated.
My error:
Fatal error: Class 'Album\Model\AlbumTable' not found in C:\Program
Files\Zend\Apache2\htdocs\zf2album\module\Album\Module.php on line 55
Album/Module.php
namespace Album;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
class Module implements ServiceProviderInterface {
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
the AlbumController.php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController; use
Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController { protected
$albumTable;
public function indexAction()
{
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
public function addAction()
{
}
public function editAction()
{
}
public function deleteAction()
{
}
public function fooAction()
{
// This shows the :controller and :action parameters in default route
// are working when you browse to /album/album/foo
return array();
}
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
} }
AlbumModel.php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class AlbumTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);
$id = (int)$album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => $id));
} }
Assuming this isn't a typo in your question, the filename for the class AlbumTable should be AlbumTable.php, not AlbumModel.php.

ZEND, Edit form

I have a Zend form to add something to database. And then I want to use this form to edit what I added to the databese. Is any possibility to use this form (fill it from database and display it???)
I have this in my controller:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'title' => $result->title,
// 'story' => $result->story,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'title' => $form->getValue("title"),
'story' => $form->getValue("story"),
);
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
In my view:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
And when I try to change something in this view I mean give any value different then NULL I have error that I can not do it so is any possibility to reuse this form? Or not?
Thanks!
Zend_Form has method populate(), which sets values of the form based on array data. So just do:
$form->populate($result->current()->toArray());
and form will be populated based on keys from array.