Yii: REST api problems - php

i'm beginner in yii and in the Yii Application Development CookBook(2nd edition) on pages 105 to 113 when i'm running this codes, add button does not work, While everything is in accordance with the text of the book, where is problem? please help me.
Some code easily run but others like this are not.
controller is:
<?php
class TodoController extends Controller
{
public function actionIndex()
{
$task = new Task();
$this->render('index', array(
'task' => $task,
));
}
public function actionTask()
{
$req = Yii::app()->request;
if($req->isPostRequest) {
$this->handlePost($req->getPost('id'),
$req->getPost('Task'));
}
elseif($req->isPutRequest) {
$this->handlePut($req->getPut('Task'));
}
elseif($req->isDeleteRequest) {
$this->handleDelete($req->getDelete('id'));
}
else {
$this->handleGet($req->getParam('id'));
}
}
private function handleGet($id)
{
if($id) {
$task = $this->loadModel($id);
$this->sendResponse($task->attributes);
}
else {
$data = array();
$tasks = Task::model()->findAll(array('order' => 'id'));
foreach($tasks as $task) {
$data[] = $task->attributes;
}
$this->sendResponse($data);
}
}
private function handlePut($data)
{
$task = new Task();
$this->saveTask($task, $data);
}
private function handlePost($id, $data)
{
$task = $this->loadModel($id);
$this->saveTask($task, $data);
}
private function saveTask($task, $data)
{
if(!is_array($data)){
$this->sendResponse(array(), 400, array('No data
provided.'));
}
// $task->setAttributes($data);
$task->attributes = $data;
if($task->save()) {
$this->sendResponse($task->attributes);
} else {
$errors = array();
foreach($task->errors as $fieldErrors) {
foreach($fieldErrors as $error) {
$errors[] = $error;
}
}
$this->sendResponse(array(), 400, $errors);
}
}
private function handleDelete($id)
{
$task = $this->loadModel($id);
if($task->delete()) {
$this->sendResponse('OK');
}
else {
$this->sendResponse(array(), 500, array('Unable to
delete task.'));
}
}
private function loadModel($id)
{
$task = Task::model()->findByPk($id);
if(!$task) {
$this->sendResponse(array(), 404, array('Task not
found.'));
}
return $task;
}
private function sendResponse($data, $responseCode = 200,
$errors = array())
{
$messages = array(
200 => 'OK',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Internal Server Error',
);
if(in_array($responseCode, array_keys($messages))) {
header("HTTP/1.0 $responseCode ".$messages[$responseCode],
true, $responseCode);
}
echo json_encode(array(
'errors' => $errors,
'data' => $data,
));
Yii::app()->end();
}
}
?>
and view is:
<?php
Yii::app()->clientScript->registerPackage('todo');
$options = json_encode(array(
'taskEndpoint' => $this->createUrl('todo/task'),
));
Yii::app()->clientScript->registerScript('todo', "todo.
init($options);", CClientScript::POS_READY);
?>
<div class="todo-index">
<div class="status"></div>
<div class="tasks"></div>
<div class="new-task">
<?php echo CHtml::beginForm()?>
<?php echo CHtml::activeTextField($task, 'title')?>
<?php echo CHtml::submitButton('Add')?>
<?php echo CHtml::endForm()?>
</div>
</div>
<script id="template-task" type="text/x-dot-template">
<div class="task{{? it.done==1}} done{{?}}" data-id="{{!it.
id}}">
<input type="checkbox"{{? it.done==1}}checked {{?}}/>
<input type="text" value="{{!it.title}}" />
Remove
</div>
</script>
I want when click on the add button, task added.

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

How to retrieve an array in Simple MVC Framework?

How can I retrieve an array in Simple MVC Framework to show error messages if some input fields are not valid?
Controller:
public function index($error)
{
$data ['title'] = $this->language->get('welcome_text');
View::renderTemplate('header', $data);
View::render('insert/form', $data);
View::renderTemplate('footer', $data);
}
public function save()
{
if (isset($_POST)) {
$data ['is_valid'] = \Helpers\Gump::is_valid($_POST, array(
'firstname' => 'required|min_len,2'
));
if ($data ['is_valid'] === true) {
// continue
} else {
$this->index($data ['is_valid']); // show error messages
die();
}
}
}
View:
<div class="alert alert-danger"><?php var_dump($error); ?></div>
... <button type="submit">Save (calls save())</button>
var_dump($error) always shows bool(false).
Basically you wasn't sent error to render, as i see.
public function index($error)
{
$data ['title'] = $this->language->get('welcome_text');
$data ['error'] = $error;
View::renderTemplate('header', $data);
View::render('insert/form', $data);
View::renderTemplate('footer', $data);
}
View
<div class="alert alert-danger"><?php var_dump($data['error']); ?></div>

More efficient way instead of using repeated if statements

I have this code:
if (strtolower($_POST['skype']) == "yummy")
echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or
$_POST['IGN'] == '' or
$_POST['pass'] == '' or
!isset($_POST['rules']) or
!isset($_POST['group']) or
strlen($_POST['pass']) <= 7)
{
redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
exit;
}
However, I would like to start reporting specific errors. For example, this is how I would do it with if statements:
...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" );
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" );
...
However that's big, messy and inefficient. What would a solution to this be?
You could use associative array like this.
function redir($var){
echo $var;
}
$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');
redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);
Create Request class for parsing data from post and get, the class helps you with validation of undefined, empty fields and Report class which helps you with throwing errors.
Here is the very simple Request class:
class Request {
protected $items = array(
'get' => array(),
'post' => array()
);
public function __construct(){
$this->items['post'] = $_POST;
$this->items['get'] = $_GET;
}
public function isPost(){
return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
}
public function isGet(){
return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
}
public function getPost($name){
return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null;
}
public function get($name){
return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
}
}
And Report class:
Class Report {
protected static $instance;
private $messages = array();
private function __construct(){}
public function getInstance(){
if(!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function addReport($message){
$this->messages[] = $message;
}
public function hasReports(){
return (!empty($this->messages)) ? true : false;
}
public function getReports(){
return $this->messages;
}
//this is not so cleaned .... it must be in template but for example
public function throwReports(){
if(!empty($this->messages)){
foreach($this->messages as $message){
echo $message."<br />";
}
}
}
}
So and how to use is for your problem:
$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
if(!$request->getPost("icq")){
$report->addMessage("you dont enter ICQ");
}
if(!$request->getPost("skype")){
$report->addMessage("you dont enter SKYPE");
}
//....etc
//if we have some reports throw it.
if($report->hasReports()){
$reports->throwReports();
}
}
The report class you can combine with sessions and throw errors after redirect, just update the class to saving reports to session instead of $messages, and after redirect if u will be have messages throw it and clear at the same time.
how about
$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
redir(...);
exit;
}
}
Perhaps something like that (reusable, but lengthy):
// validation parameters
$validation = array(
'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
'IGN' => array('check' => 'not_empty', 'error' => 'IGN empty'),
'pass' => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
'group' => array('check' => 'set', 'error' => 'group unset'),
'rules' => array('check' => 'set', 'error' => 'group unset')
);
// validation class
class Validator {
private $params;
private $check_methods = array('not_empty', 'size', 'set');
public function __construct($params){
$this->params = $params;
}
private function not_empty($array, $key){
return $array[$key] == '';
}
private function size($array, $key ,$s){
return strlen($array[$key]) < $s;
}
private function set($array, $key){
return isset($array[$key]);
}
private handle_error($err, $msg){
if ($err) {
// log, redirect etc.
}
}
public function validate($data){
foreach($params as $key => $value){
if (in_array($value['check'], $this->check_methods)){
$params = $value['params'];
array_unshift($params, $data, $key);
$this->handler_error(call_user_func_array(array($this,$value['check']),
$params),
$value['error']);
}
}
}
};
// usage
$validator = new Validator($validation);
$validator->validate($_POST);
Just expand the class with new checks, special log function etc.
Warning: untested code.
This is how I do error reporting now:
$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
if ($current == '' || $current == null) {
//The error should be stored in a session, but the question asked for URL storage
redir('/apply/?fail='.urlencode($errors[$current]));
}
}

Cake php ajax layout cache

After any ajax request all subsequent non ajax request is returning with ajax layout instead of default layout.
Obs:
Ocurrs only on production enviroment.
Configure::write('Cache.disable', true); // Don't have any effect!
Cake Version 2.4.4
After 20 ~ 30 seconds the layout (default) is rendered.
config/core.php is identical.
I don't no why , and i loose 8 hours on that, any tip?
The controller (But any ajax on any controller cause the problem:
<?php
App::uses('AppController', 'Controller');
class NewslettersController extends AppController
{
public $paginate = array(
'limit' => 20,
'paramType' => 'querystring',
'order' => array(
'Newsletter.created' => 'DESC'
)
);
public function beforeFilter()
{
parent::beforeFilter();
$this->Auth->allow(array('add','push'));
}
public function admin_index()
{
$this->set('dataGrid', $this->paginate('Newsletter'));
}
public function admin_view($id = null)
{
$this->Newsletter->id = $id;
$result = $this->Newsletter->read();
if (!$result) {
$this->setFlashMessage('Cadastro não encontrado', 'error', array('action' => 'index'));
return false;
}
$this->set('dataGrid', $result);
}
public function admin_delete($id = null)
{
$this->Newsletter->id = $id;
if (!$this->Newsletter->exists()) {
$this->Session->setFlash('O item solicitado não foi encontrado!', 'alert_error');
$this->setFlashMessage('O item solicitado não foi encontrado!', 'error', array('action' => 'index'));
}
try {
if ($this->Newsletter->delete($id, false)) {
$this->setFlashMessage('Item excluído com sucesso!', 'success', array('action' => 'index'));
}
} catch (Exception $e) {
$this->setFlashMessage('Não foi possivel excluir este item pois existem itens atrelados a ele', 'error', array('action' => 'index'));
}
}
public function admin_search()
{
$this->autoRender = false;
$conditions = null;
if (isset($this->request->query['search']) && !empty($this->request->query['search'])) {
$conditions[] = array(
'OR' => array(
'Newsletter.name LIKE' => '%' . $this->request->query['search'] . '%',
'Newsletter.email LIKE' => '%' . $this->request->query['search'] . '%',
)
);
$this->paginate['conditions'] = $conditions;
$this->set('dataGrid', $this->paginate());
$this->render('admin_index');
}
}
//######################
//# FRONTEND #
//######################
public function push()
{
if($this->Newsletter->save($this->request->data))
{
$response = array("result"=>true,"id"=>$this->Newsletter->id);
}
else
{
$response = array("result"=>false,"errors"=>$this->Newsletter->validationErrors);
}
return new CakeResponse(array("body" => json_encode($response),"type" => "json"));
}
}
?>
You have to differentiate the layout for ajax in the method, please the following changes I made in the above code:
...
class NewslettersController extends AppController
{
public layout = 'default';
...
public function push() // if this is ajax function
{
$this->layout = 'ajax'; //put this for ajax functions only
....
}
...
}
Hope it helps!

The request has been black-holed

when i am upload multiple images i found The request has been black-holed
Error: The requested address '/admins/uploadimage1' was not found on this server.
my contoller function
public function uploadimage1()
{
if($this->request->is('post'))
{
$a=$this->data['Admins']['imgs'];
print_r($a);
}
}
view file
<?php echo $this->Form->create('Admins',array('controller'=>'Admins','action'=>'uploadimage1', 'type'=>'file', 'accept-charset'=>'utf-8'));?>
<table width="95%">
<tr><td><b>Image Title</b></td><td><?php echo $this->Form->input('title', array('type' => 'text', 'class'=>'input-block-level','placeholder'=>'Image Title' ,'label'=>false )); ?></td></tr>
<tr><td></td><td>
<?php echo $this->Form->input('imgs.',array('type'=>'file', 'label'=>false, 'multiple')); ?></td></tr>
<tr><td></td><td><?php echo $this->Html->image('../img/adminimages/upload.jpg', array('id'=>'blah','height'=>'100px','width'=>'100px')); ?></td></tr>
<tr><td></td><td>
<?php
foreach ($Retailers as $Retailer)
{
$r_id=$Retailer['Retailer']['id'];
echo $this->Form->input('r_id', array('type'=>'hidden','value'=>$r_id)); }?>
<?php echo $this->Form->submit('Submit',array('class' => 'button')); ?></td></tr></table>
<?php echo $this->Form->end();
my controller
<?php
App::uses('AppController', 'Controller');
class AdminsController extends AppController
{
public $name='Storelocators/Admins';
/**
* This controller does not use a model
*
* #var array
*/
public $uses = array('Admin','Retailer','Gallery');
public function beforeFilter() {
$this->Security->unlockActions = ('uploadimage1');
$this->Auth->allow('login','logout','signup','abhi');
}
public function beforeRender() {
parent::beforeRender();
}
public function index()
{
$this->layout='admin';
}
public function signup()
{
$this->layout='admin';
if($this->request->is('post'))
{
$admin_data=array (
'username'=>$this->data['Admins']['username'],
'email'=>$this->data['Admins']['email'],
'type'=>'Admin',
'password'=>$this->Auth->password($this->data['Admins']['password']));
$this->Admin->save($admin_data);
$this->Session->setFlash(__('Your are successfully Sign up.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
public function login(){
$this->layout='admin';
if($this->request->is('post')){
if($this->Auth->login()){
$name = $this->Auth->user('username');
$this->Session->write('a', $name);
$this->redirect($this->Auth->redirect());
}
else{
$this->Session->setFlash(__("Your email/password combination was incorrect.", true));
$this->redirect($this->referer());
}
}
}
public function logout(){
$this->Session->delete('a');
$this->layout = false;
$this->autoRender = false;
$this->Session->setFlash(__('You have logout successfully.', true), 'default', array('class' => 'message success'));
$this->redirect($this->Auth->logout());
}
public function form()
{
$this->layout='admin';
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']) && !empty($this->data['Admins']['imgs1']['name']) )
{
$file=$this->data['Admins']['imgs'];
$file1=$this->data['Admins']['imgs1'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/UploadImages/' .$date1.'_'.$file['name'] );
move_uploaded_file($file1['tmp_name'], WWW_ROOT . 'img/adminimages/UploadImages/' .$date1.'_'.$file1['name'] );
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$n1 = $this->request->data['Admins']['imgs1'] = $file1['name'];
$date=date('d/m/Y');
$days1=$this->data['Admins']['days'];
$day=implode(",",$days1);
$r_type1=$this->data['Admins']['r_type'];
$r_types=implode(",",$r_type1);
$my_data=array(
'name'=>ucfirst($this->data['Admins']['name']),
'address'=>ucfirst($this->data['Admins']['address']),
'province'=>ucfirst($this->data['Admins']['province']),
'region'=>ucfirst($this->data['Admins']['region']),
'city'=>ucfirst($this->data['Admins']['city']),
'nation'=>ucfirst($this->data['Admins']['nation']),
'r_type'=>$r_types,
'open_hours'=>$this->data['Admins']['hours1'].','.$this->data['Admins']['hours2'],
'days'=>$day,
'description'=>ucfirst($this->data['Admins']['description']),
'logo_image'=>$date1.'_'.$n,
'main_image'=>$date1.'_'.$n1,
'status'=>'Active',
'create_date'=>$date
);
$this->Retailer->save($my_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect(array('controller'=>'Admins','action'=>'uploadimage'));
}
}
}
}
public function addname()
{
$this->layout='admin';
}
public function tabel()
{
$this->layout='admin';
$this->set('Retailers' , $this->Retailer->find('all'));
}
public function uploadimage()
{
$this->layout='admin';
$this->set('Retailers', $this->Retailer->find('all', array('order'=>array('Retailer.id DESC'),'limit'=>'1')));
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']))
{
$file=$this->data['Admins']['imgs'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/GalleryImages/' .$date1.'_'.$file['name'] );
$date=date('d/m/Y');
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$gal_data=array(
'r_id'=>$this->data['Admins']['r_id'],
'image'=>$date1.'_'.$n,
'title'=>ucfirst($this->data['Admins']['title']),
'create_date'=>$date);
$this->Gallery->save($gal_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
}
}
public function addimage($id)
{
$this->layout='admin';
$ir=$this->Retailer->findById($id);
if($ir['Retailer']['status']=='Active')
{
$this->set('Gs',$this->Gallery->find('all', array('conditions'=>array('Gallery.r_id'=>$id))));
//print_r($Gs);
//print_r($Gallerys);
//exit();
if(!empty($id))
{
if($this->request->is('post'))
{
if(!empty($this->data['Admins']['imgs']['name']))
{
$file=$this->data['Admins']['imgs'];
$ary_ext=array('jpg','jpeg','gif','png');
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
// $ext1 = substr(strtolower(strrchr($file1['name'], '.')), 1); //get the extension
if(in_array($ext,$ary_ext))
{
$date1=date('dmYhis');
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/adminimages/GalleryImages/' .$date1.'_'.$file['name'] );
$date=date('d/m/Y');
$n = $this->request->data['Admins']['imgs'] = $file['name'];
$gal_data=array(
'r_id'=>$id,
'image'=>$date1.'_'.$n,
'title'=>ucfirst($this->data['Admins']['title']),
'create_date'=>$date);
$this->Gallery->save($gal_data);
$this->Session->setFlash(__('Your Data Succefully Inserted.', true), 'default', array('class' => 'sukses'));
$this->redirect($this->referer());
}
}
}
}
}
else
{
$this->Session->setFlash(__('First Active this Retailer', true));
$this->redirect($this->referer());
}
}
public function uploadimage1()
{
if($this->request->is('post'))
{
$a=$this->data['Admins']['imgs'];
print_r($a);
}
}
public function updatestatus($id)
{
$urs=$this->Retailer->findById($id);
if($urs['Retailer']['status']=='Active')
{
$this->Retailer->updateAll(array('Retailer.status' => '"De-Active"'), array('Retailer.id' => $id));
$this->redirect(array('controller'=>'Admins', 'action'=>'tabel'));
}
else
{
$this->Retailer->updateAll(array('Retailer.status' => '"Active"'), array('Retailer.id' => $id));
$this->redirect(array('controller'=>'Admins', 'action'=>'tabel'));
}
}
public function gallery()
{
$this->layout='admin';
//$this->set('Gs',$this->Gallery->find('all'));
//$this->set('Gs',$this->Gallery->find('all', array('joins' => array(array('table' => 'retailers','alias' => 'Re','type' => 'inner','foreignKey' => true,'conditions'=> array('Re.id = Gallery.r_id'))))));
$this->Set('Gs',$this->Gallery->find('all',array('fields'=> array('*','*'), 'joins'=> array( array('table'=>'retailers', 'type'=>'inner','conditions'=>array('Gallery.r_id=retailers.id','retailers.status'=>'Active'))))));
// print_r($Gs);
// $db =& ConnectionManager::getDataSource('default');
// $db->showLog();
// exit();
}
} ?>
This is my controller.
Its not a issue on multiple upload. Its showing bcz of Security Component. You can bypass this by adding $this->Security->unlockActions = array('your actions');
Add this code to your controller.....
public function beforeFilter(){
$this->Security->unlockActions = array('action_name');
}
You have to change the Security config.
Right:
$this->Security->config('unlockedActions', 'action_name');
Wrong:
$this->Security->unlockedActions = ['action_name'];

Categories