Zend 2.x, setValue from url - request

i want to setValue in Form class depending on GET request. To set value in form i do sth like this :
class BookingForm extends Form
{
$this->add(array(
'name' => 'end',
'type' => 'Text',
'options' => array(
'label' => 'Date to',
),
'attributes' => array(
'value' => '2013-09-18 15:45',
),
));
}
but it's hard coded and i want avoid this, is there method $this->getRequest()->get('var to be extracted from url') ??

I founded solution in :
class BookingController extends AbstractActionController
{
...
$get = $request->getQuery('start');
$get = str_replace('_', ' ', $get);
$form->get('start')->setValue($get);
...
}
and that's all.

If you have configured a router you can use this:
// router
'index' => array(
'type' => 'Segment',
'options' => array(
'route' => '/myvar/:start',
'constraints' => array(
'template' => '[a-zA-Z0-9_-]+'
),
'defaults' => array(
'controller' => 'module/controller',
'action' => 'index',
),
),
),
Controller.php
class BookingController extends AbstractActionController
{
...
$get = $this->params("start", "");
$form->get('start')->setValue($get);
...
}

Related

need to change field value before insert it into database using helper form

I create a Helper list with my database, to pu content in field "cont" i use TinyMCE, but whene i write value into db html element not stores, how i can write my field with html code?
if i use db class of prestashop i can use htmlentities function to store my data, but I dont understand how to use this in my fields_form array
Db::getInstance()->autoExecute(_DB_PREFIX_.'pdf_files', array(
'content' => pSQL(htmlentities($content))
),
'INSERT');
this code works just like i want, in my code, I don't realy know where i can use
htmlentities($content)
here is my object model and my controller
<?php
class PdfData extends ObjectModel{
public $id;
public $name;
public $cont;
public $head_1;
public $head_2;
public $head_3;
public $head_4;
public $head_5;
public $inst;
public $facebook;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'pdf_files',
'primary' => 'id',
'fields' => array(
'name' => array(
'type' => 'varchar',
'validate' => 'isGenericName',
'required' => true,
'class' => 'lg'
),
'head_1' => array(
'type' => 'varchar',
'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'head_2' => array(
'type' => 'varchar',
'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'head_3' => array(
'type' => 'varchar',
'value' => 'lal',
'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'head_4' => array(
'type' => 'varchar',
'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'head_5' => array(
'type' => 'varchar',
'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'inst' => array(
'type' => 'bool',
//'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'facebook' => array(
'type' => 'bool',
//'validate' => 'isGenericName',
'required' => false,
'class' => 'lg'
),
'cont' => array(
'type' => 'text',
'validate' => 'isString',
'required' => false,
'class' => 'lg'
),
),
);
}
class PdfListController extends ModuleAdminController{
const CONTROLLER_NAME = 'PdfList';
public $displayName = 'PDFer';
public function __construct(){
$this->bootstrap = true;
$this->className = 'PdfData';
$this->table = 'pdf_files';
//Tools::getValue('id_product');
$this->fields_list = array(
'id' => array(
'title' => 'ID',
'width' => 'auto',
'type' => 'int'
),
'name' => array(
'title' => $this->l('Name'),
'width' => 'auto',
'type' => 'varchar'
),
'cont'=>array(
'title' => $this->l('content'),
'width' => 'auto',
'type' => 'varchar'
)
);
$this->identifier = 'id';
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')
)
);
parent::__construct();
$this->callAction();
}
private function callAction() {
$actionName = 'process' . ucfirst(trim($_GET['action']));
if(method_exists($this, $actionName)) {
$this->$actionName();
}
}
public function renderList()
{
$this->addRowAction('download');
$this->addRowAction('delete');
$this->addRowAction('edit');
return parent::renderList();
}
public function processDelete()
{
$sql= "DELETE FROM `"._DB_PREFIX_."pdf_files` WHERE `ps_pdf_files`.`id` = ". Tools::getValue('id');
$return = Db::getInstance()->execute($sql);
return $return;
}
public function processDownload()
{
//var_dump(Configuration::get(pdfer::HEAD_3));die;
require_once _PS_MODULE_DIR_ . 'pdfer/classes/pdf/HTMLTemplatePdf.php';
$sql = "SELECT * FROM "._DB_PREFIX_."pdf_files WHERE id = " . Tools::getValue('id');
$pdf = new stdClass();
$pdfData = Db::getInstance()->getRow($sql);
$pdf->cont = html_entity_decode($pdfData["cont"]);
$pdf->name = $pdfData["name"];
$pdf->head_1 = $pdfData["head_1"];
$pdf->head_2 = $pdfData["head_2"];
$pdf->head_3 = $pdfData["head_3"];
$pdf->head_4 = $pdfData["head_4"];
$pdf->head_5 = $pdfData["head_5"];
//$pdf->header = html_entity_decode($pdfData["head"]);
$pdf->path_logo = _PS_MODULE_DIR_.'pdfer/views/templates/images/header_logo.jpg';
$pdf->path_footer = _PS_MODULE_DIR_.'pdfer/views/templates/images/footer_signature.jpg';
$pdf->path_facebook = _PS_MODULE_DIR_.'pdfer/views/templates/images/facebook.jpg';
$pdf->path_inst = _PS_MODULE_DIR_.'pdfer/views/templates/images/inst.jpg';
$pdf->include_inst = (string)Configuration::get(pdfer::CHECK_IMAGE_INST);
$pdf->include_facebook = (string)Configuration::get(pdfer::CHECK_IMAGE_FACEBOOK);
$pdfGen = new PDF($pdf, 'Pdf', $this->context->smarty);
$content = $pdfGen->render(false);
header("ContentType: application/pdf");
header("Content-disposition: attachment; filename=\"$pdf->name.pdf\"");
header("Content-Length: " . strlen($content));
echo $content;
exit;
}
public function displayDownloadLink($token = null, $id, $name = null)
{
$tpl = $this->createTemplate('helpers/list/list_action_view.tpl');
if (!array_key_exists('Download', self::$cache_lang))
self::$cache_lang['Download'] = $this->l('Download');
$tpl->assign(array(
'href' => static::$currentIndex .'&'.$this->identifier.'='.$id.'&action=download&'.$this->table.'&token='.($token != null ? $token : $this->token),
'action' => self::$cache_lang['Download'],
'id' => $id
));
return $tpl->fetch();
}
/**
* #return string
*/
public function renderForm() {
// Building the Add/Edit form
$this->fields_value['head_1'] = (string)Configuration::get(pdfer::HEAD_1);
$this->fields_value['head_2'] = (string)Configuration::get(pdfer::HEAD_2);
$this->fields_value['head_3'] = (string)Configuration::get(pdfer::HEAD_3);
$this->fields_value['head_4'] = (string)Configuration::get(pdfer::HEAD_4);
$this->fields_value['head_5'] = (string)Configuration::get(pdfer::HEAD_5);
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('New Pdf')
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'class' => 'lg',
'required' => true,
'desc' => $this->l('adadada'),
),
array(
'type' => 'textarea',
'label' => $this->l('Content'),
'name' => 'cont',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'head_1',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'head_2',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'head_3',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'head_4',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'head_5',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'inst',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
array(
'type' => 'hidden',
'label' => $this->l('Content'),
'name' => 'facebook',
//'class' => 'lg',
'required' => false,
'autoload_rte' => true,
),
),
'submit' => array(
'title' => $this->l('Save'),
//'class' => 'button'
)
);
return parent::renderForm();
}
}
here's picture, in first i enter some text, 2 i edit, but there is text only
You should not be using pSQL(htmlentities($content)) to insert content to the database table.
Tye replacing it with Tools::htmlentitiesUTF8($content) while saving HTML content and use Tools::htmlentitiesDecodeUTF8($content) when you extract data from the database.

Cakephp: Spurious login message

I do not have a users login page in Cakephp(I have another login page and associated controller that works fine)
Every so often, especially if I have not used the app for a while I get a message stating that my users/login page is missing.
I have searched within the text of all files in my subdirectory, but am at a loss as to where this message originates.
Any ideas?
You must be logged in to view this page.
Missing Controller
Error: UsersController could not be found.
Error: Create the class UsersController below in file: app\Controller\UsersController.php
<?php
class UsersController extends AppController {
}
Notice: If you want to customize this error message, create app\View\Errors\missing_controller.ctp
**Stack Trace**
APP\webroot\index.php line 111 → Dispatcher->dispatch(CakeRequest, CakeResponse)
$Dispatcher->dispatch(
new CakeRequest(),
new CakeResponse()
);
object(CakeRequest) {
params => array(
'plugin' => null,
'controller' => 'users',
'action' => 'login',
'named' => array(),
'pass' => array()
)
data => array()
query => array()
url => 'users/login'
base => '/checks'
webroot => '/checks/'
here => '/checks/users/login'
[protected] _detectors => array(
'get' => array(
'env' => 'REQUEST_METHOD',
'value' => 'GET'
),
'post' => array(
'env' => 'REQUEST_METHOD',
'value' => 'POST'
),
'put' => array(
'env' => 'REQUEST_METHOD',
'value' => 'PUT'
),
'delete' => array(
'env' => 'REQUEST_METHOD',
'value' => 'DELETE'
),
'head' => array(
'env' => 'REQUEST_METHOD',
'value' => 'HEAD'
),
'options' => array(
'env' => 'REQUEST_METHOD',
'value' => 'OPTIONS'
),
'ssl' => array(
'env' => 'HTTPS',
'value' => (int) 1
),
'ajax' => array(
'env' => 'HTTP_X_REQUESTED_WITH',
'value' => 'XMLHttpRequest'
),
'flash' => array(
'env' => 'HTTP_USER_AGENT',
'pattern' => '/^(Shockwave|Adobe) Flash/'
),
'mobile' => array(
'env' => 'HTTP_USER_AGENT',
'options' => array(
[maximum depth reached]
)
),
'requested' => array(
'param' => 'requested',
'value' => (int) 1
)
)
[protected] _input => ''
}
Appcontroller code follows:
App::uses('Controller', 'Controller');
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* #package app.Controller
* #link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
// added the debug toolkit
// sessions support
// authorization for login and logut redirect
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'instructors', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'instructors', 'action' => 'login'),
'authError' => 'You must be logged in to view this page.',
'loginError' => 'Invalid Username or Password entered, please try again.'
));
// only allow the login controllers only
public function beforeFilter() {
$this->Auth->allow('login','index');
//allow access to currently logged in user to all programs
$this->set('logged_in',$this->Auth->loggedIn());
$this->set('current_user',$this->Auth->user());
}
public function isAuthorized($user) {
return true;
}
}
This sounds like a routing issue to me. There are a number of things which I would check.
1) Routing
Make sure that you have a route for /checks/users/login, which either resolves to your UsersController::login() method or redirects.
2) Auth setup
I would make sure that your login url specified in your Auth config specifically removes and prefix routing and plugin routing.
<?php
// If you were using 'admin' prefix routing
'loginRedirect' => array('controller' => 'instructors', 'action' => 'index', 'admin' => false, 'plugin' => false)
3) Login method
Double check that you have a UsersController::login() method defined in your controller.
So in summary, I believe the issue is caused because you are in /checks routing, and you are trying to redirect the user to your login, but the /checks routing it sticking, meaning you're actually trying to redirect to /checks/users/login which doesn't exist, which is why a 404 is being generated.

Why cakephp image uploader plugin isnot working?

I am trying to upload image during ajax call. For this, I used a plugin for thumb nail creation.But Its not inserting any data and thumbnail also.
I am giving my plugin link and also controller code and model :
https://github.com/josegonzalez/cakephp-upload
$club_id = $this->request->data['Photo']['club_id'];
$id = $this->Auth->user();
$this->request->data['Photo']['user_id'] = $id["id"];
$this->request->data['Photo']['club_id'] = $club_id;
$this->request->data['Photo']['photo_type'] = "club";
$this->request->data['Photo']['profile_picture'] = "no";
$this->Photo->save($this->request->data);
AND MODEL CODE :
public $actsAs = array(
'Upload.Upload' => array(
'picture' => array(
'path' => '{ROOT}webroot{DS}img{DS}{model}{DS}{field}{DS}',
'fields' => array(
'dir' => 'picture_dir'
),
'thumbnailSizes' => array(
'thumb' => '100x100'
), 'thumbnailMethod' => 'php'
)
)
);
My view file is :
$this->Form->create($id, array('type' => 'file', "id" => "multiform"));
$this->Form->input('picture', array('type' => 'file'));
$this->Form->button('Upload', array('type' => 'submit', "id" => "club_upload"));
$this->Form->end();
Its not creating thumbnail and data in database. I am stuck on it, any idea would help me.
This should work:
public $actsAs = array(
'Upload.Upload' => array(
'path' => '{ROOT}webroot{DS}img{DS}{model}{DS}{field}{DS}',
'fields' => array(
'dir' => 'picture_dir'
),
'thumbnailSizes' => array(
'thumb' => '100x100'
),
'thumbnailMethod' => 'php',
'deleteOnUpdate' => true
)
);
EDIT:
In view file:
$this->Form->create('Photo', array('type' => 'file', "id" => "multiform"));
Passing id as form name is bad idea.
Now you can access your data like this:
$this->request->data['Photo']['picture']
You may have add form for club_id field.

CakeDC Search and Tag plugin - search for multiple tags

Hopefully I'm missing something simple here. I'm using the CakeDC Search and Tags plugin for my cake (2.3.4) app.
Along with generic search by field functionality I want the user to be able to search by tags. I've almost got this working but the search will only display results if you search for a single tag not multiples. For example, if I add an article with the following tags - black, white, red. The article will only show in the search results if I search for a single tag (say, black) and not all 3, or even 2... What am I missing?
Heres my code:
Article.php model
class Article extends AppModel {
public $actsAs = array(
'Upload.Upload' => array(
'screenshot1' => array (
'fields' => array (
'dir' => 'dir'
),
'thumbnailMethod' => 'php',
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'thumb' => '80x80'
),
),
),
'Search.Searchable',
'Tags.Taggable'
);
// Search plugin filters
public $filterArgs = array(
'title' => array('type' => 'like'),
'environment' => array('type' => 'like'),
'description' => array('type' => 'like'),
'error' => array('type' => 'like'),
'cause' => array('type' => 'like'),
'resolution' => array('type' => 'like'),
'live' => array('type' => 'value'),
'synced' => array('type' => 'value'),
'tags' => array('type' => 'subquery', 'method' => 'findByTags', 'field' => 'Article.id'),
array('name' => 'search', 'type' => 'query', 'method' => 'filterQuery'),
);
// This is the OR query that runs when the user uses the client side signle field search
public function filterQuery($data = array()) {
if(empty($data['search'])) { // search is the name of my search field
return array();
}
$query = '%'.$data['search'].'%';
return array(
'OR' => array(
'Article.title LIKE' => $query,
'Article.description LIKE' => $query,
'Article.error LIKE' => $query,
)
);
}
// Find by tags method
public function findByTags($data = array()) {
$this->Tagged->Behaviors->attach('Containable', array('autoFields' => false));
$this->Tagged->Behaviors->attach('Search.Searchable');
$query = $this->Tagged->getQuery('all', array(
'conditions' => array('Tag.name' => $data['tags']),
'fields' => array('foreign_key'),
'contain' => array('Tag')
));
return $query;
}
public $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category',
'joinTable' => 'articles_categories',
'foreignKey' => 'article_id',
'associationForeignKey' => 'category_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Tag' => array('with' => 'Tagged')
);
Controller method
public function admin_advancedSearch() {
// Disable validation for this action
$this->Article->validate = array();
// For search plugin
$this->Prg->commonProcess();
// Set searched for details
$this->set('searchedFor', $this->passedArgs);
// If passed args are all empty
if ($this->passedArgs) {
if (empty($this->passedArgs['title']) AND
empty($this->passedArgs['environment']) AND
empty($this->passedArgs['description']) AND
empty($this->passedArgs['error']) AND
empty($this->passedArgs['cause']) AND
empty($this->passedArgs['resolution']) AND
empty($this->passedArgs['live']) AND
empty($this->passedArgs['synced']) AND
empty($this->passedArgs['tags'])) {
$this->Session->setFlash('Please enter at least one search criteria', 'flash_failure');
// Set this var for checks in view
$this->set('emptySeach', true);
} else {
$paginateConditions = $this->Article->parseCriteria($this->passedArgs);
$this->paginate = array('conditions' => array(
$paginateConditions),
'limit' => 10,
'order' => array('Article.modified' => 'DESC'));
$this->set('articles', $this->paginate());
// Count number of results
$count = 0;
foreach ($this->paginate() as $result) {
$count++;
}
$this->set('resultsCount', $count);
// Search was not empty - set flag for view
$this->set('emptySeach', false);
}
}
// Set layout
$this->layout = 'admin';
//debug($this->passedArgs);
}
All plugins are loaded successfully from bootstrap, searches work fine without tags. Searches with tags only work if one tag is entered....
*EDIT *
If I debug $query from the findByTags method I get this:
'SELECT `Tagged`.`foreign_key` FROM `knowledgebase`.`tagged` AS `Tagged` LEFT JOIN `knowledgebase`.`tags` AS `Tag` ON (`Tagged`.`tag_id` = `Tag`.`id`) WHERE `Tag`.`name` = 'kia, rio, red''
So it looks like its trying to find a single tag with all the searched for tags in its name. How can I make the WHERE part an IN?
For example:
WHERE `Tag`.`name` IN ('kia', 'rio', 'red')
Thanks
Use the "method" https://github.com/cakedc/search#behavior-and-model-configuration key her to pass the search args to a customized method.
The example here shows you exactly how this works https://github.com/cakedc/search#full-example-for-modelcontroller-configuration-with-overriding
public $filterArgs = array(
'some_related_table_id' => array('type' => 'value'),
'search'=> array('type' => 'like', 'encode' => true, 'before' => false, 'after' => false, 'field' => array('ThisModel.name', 'OtherModel.name')),
'name'=> array('type' => 'query', 'method' => 'searchNameCondition')
);
public function searchNameCondition($data = array()) {
$filter = $data['name'];
$cond = array(
'OR' => array(
$this->alias . '.name LIKE' => '' . $this->formatLike($filter) . '',
$this->alias . '.invoice_number LIKE' => '' . $this->formatLike($filter) . '',
));
return $cond;
}
Inside your custom method explode() the tags and make them an array so that CakePHP is using them as IN() or better (in can become slow) make it a chain of AND or OR.

FilesSize validator in Model using factory

That's my model SiteDesign.php in Object\Model:
namespace Object\Model;
use Zend\Validator\StringLength;
use Zend\Validator\NotEmpty;
use Zend\Validator\File\Size;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class SiteDesign {
public $logo_filename;
public $background_image;
public $background_color;
public function exchangeArray($data) {
$this->logo_filename = (isset($data['logo_filename'])) ? $data['logo_filename'] : null;
$this->background_image = (isset($data['background_image'])) ? $data['background_image'] : null;
$this->background_color = (isset($data['background_color'])) ? $data['background_color'] : null;
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception('Not used');
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'logo_filename',
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'FilesSize',
'options' => array(
'max' => 4 * 1024,
'messages' => array(
Size::TOO_BIG => 'Размерът на логото не може да надвишава 5MB.',
),
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'background_image',
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'FilesSize',
'options' => array(
'max' => 4 * 1024,
'messages' => array(
Size::TOO_BIG => 'Размерът на изображението за фон не може да надвишава 5MB.',
),
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'background_color',
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
but there's an error message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for FilesSize
so is it possible to define a FilesSize validator directly in the model using factory or not? And is this the right way to do it? Thanks in advance.
As of Zend\Validator\ValidatorPluginManager (which is responsible of instantiating validators by name) the correct name is `"FileSize" (you got too many "s" in there).

Resources