Here is my code:
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->_forward('search');
}
public function searchAction()
{
if($this->getRequest()->isGet())
{
$form = $this->getForm();
$value = $form->getValue('search');
echo "'", $value, "'"; // <-- prints ''
}
$this->view->form = $this->getForm();
}
public function getForm()
{
$form = new Zend_Form();
$form->setAction('/index/search')
->setMethod('get');
$search = $form->createElement('text', 'search');
$search->addFilter('StripTags')
->addFilter('StringTrim');
// Add elements to form:
$form->addElement($search)
->addElement('submit', 'submit', array('label' => 'Search'));
return $form;
}
}
In searchAction() $value is always blank even after I submit the form and I see the data in the URL. What is the problem?
EDIT: I fixed getValue() to getValues() but it still isn't working.
Before you are able to use ->getValue(); you have to validate the form.
public function searchAction()
{
if($this->getRequest()->isGet())
{
$form = $this->getForm();
if ($form->isValid()) {
$value = $form->getValue('search');
echo "'", $value, "'"; // <-- prints ''
} else {
// what ever
}
}
$this->view->form = $this->getForm();
}
You need to pass $this->_request->getParams() to $form->isValid(), otherwise the form will not have any values to work with.
The function you want is getValue, not getValues.
A subtle difference but they do two totally different things.
Related
For the past couple months I have been pulling hair out trying to get forms to work with Staticpublisher module for Silverstripe.
The form is built properly on the frontend but does not send emails or redirect to the success page when static publisher is enabled.
I have set up the form as follows:
Page.php
class Page extends SiteTree {
............
public function allPagesToCache() {
$urls = array();
$pages = DataObject::get("Page");
// ignored page types
$ignored = array(
'EnquiryForm'
);
foreach($pages as $page) {
if (!in_array($page->Classname, $ignored)) {
$urls = array_merge($urls, (array)$page->subPagesToCache());
}
}
return $urls;
}
public function subPagesToCache() {
$urls = array();
$urls[] = $this->Link();
if ($this->ProvideComments) {
$urls[] = Director::absoluteBaseURL() . "CommentingController/rss/SiteTree/" . $this->ID;
}
return $urls;
}
public function pagesAffectedByChanges() {
$urls = $this->subPagesToCache();
if($p = $this->Parent) $urls = array_merge((array)$urls, (array)$p->subPagesToCache());
return $urls;
}
}
............
class Page_Controller extends ContentController {
private static $allowed_actions = array('EnquiryForm');
public function init() {
parent::init();
}
public function EnquiryForm() {
return new EnquiryForm($this, 'EnquiryForm');
}
}
EnquiryForm.php
class EnquiryForm extends Form {
public function __construct($controller, $name) {
// Form fields
$fields = new FieldList(
TextField::create('Name')->setAttribute('placeholder', 'Name'),
EmailField::create('Email')->setAttribute('placeholder', 'Email'),
TextField::create('Phone')->setAttribute('placeholder', 'Phone'),
TextareaField::create('Message')->setAttribute('placeholder', 'Message')
);
// Strict method check
$strictFormMethodCheck = true;
// Form action
$actions = new FieldList(
new FormAction('sendEmail', 'Submit')
);
// Required fields
$validator = new RequiredFields('Name', 'Email', 'Phone', 'Message');
parent::__construct($controller, $name, $fields, $actions, $validator);
}
public function sendEmail($data) {
// Submit function for contact form above
if (isset($data) && !empty($data)) {
// Phone number default
$visitorPhone = !empty($data['Phone']) ? $data['Phone'] : '(Not supplied)';
// Get clients email from the CMS
$clientEmail = SiteConfig::current_site_config()->Email;
// Extra emails to send to (CC)
$ccEmails = SiteConfig::current_site_config()->CCEmails;
// Setup email
$email = new Email();
$email->setTo($clientEmail);
$email->setCc($ccEmails);
$email->setFrom($data['Email']);
$email->setSubject("New website enquiry received from " . ucwords($data["Name"]));
// Email message
$messageBody = "
<h1>Enquiry Via The " . SiteConfig::current_site_config()->Title . " Website</h1>
<h2>Details</h2>
<ul>
<li><strong>Name:</strong> " . $data["Name"] . "</li>
<li><strong>Email:</strong> <a href='mailto:{$data['Email']}'>{$data['Email']}</a></li>
<li><strong>Phone:</strong> " . $visitorPhone . "</li>
</ul>
<h2>Message</h2>
<p>{$data['Message']}</p>
";
$email->setBody($messageBody);
$email->send();
SESSION::set('Post', $data);
$customSuccessPage = $this->EnquirySuccessPage()->Link();
Controller::curr()->redirect($successLink);
}
}
public function forTemplate() {
return $this->renderWith(array($this->class, 'Form'));
}
}
I am then including the form in various templates with {$EnquiryForm}.
I would appreciate any help with this greatly.
Try:
Place the sendEmail() function within Page_Controller
add 'sendEmail' to the $allowed_actions of the Page_Controller class
Replace Controller::curr()->redirect with $this->redirect
Within the EnquiryForm function replace: return new EnquiryForm($this, 'EnquiryForm'); with return new EnquiryForm($this, 'sendEmail');
Try updating the allowed_action with the below mentioned code. And also rebuild dev/build the site
private static $allowed_actions = array('EnquiryForm'.'sendEmail');
Im busy with an image moving function so im overriding some controller functions, and unfortuantly i required the items id for the image name so i changed form save() to postSaveHook() as i was not able to get the item id in save() but now im facing another problem i cant set form data to the newly renamed image.
Here's the code:
public function postSaveHook($model, $validData){
$item = $model->getItem();
$id = $item->get('id');
$path = JPath::clean(JPATH_SITE. DS ."images". DS ."menu_slider". DS );
$input=JFactory::getApplication()->input;
$input->get('jform', NULL, NULL);
$src_image = $this->moveOriginal($path,$id);
$imageTest = $this->findImages($src_image);
if(!empty($imageTest)){
foreach($imageTest as $images){
$this->createImageSlices($images,$src_image,$path);
}
}else{
echo 'all images are there';
}
/*this part no longer works*/
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['image'] = 'images'.DS.'menu_slider'.DS.'original'.DS.$src_image;
$input->post->set('jform',$data);
return parent::postSaveHook($model, $validData);
}
is there anyway i can save the data from this? or if i revert back to save, how would i get the id?
Any Help Greatly Appreciated.
I tried different ways and the absolute safest way for me was to add the following code in the model
class DPCasesModelCase extends JModelAdmin {
public function save($data) {
new EventHandler(JDispatcher::getInstance(), $this);
return parent::save($data);
}
}
class EventHandler extends JEvent {
private $model = null;
public function __construct(&$subject, $model) {
parent::__construct($subject);
$this->model = $model;
}
public function onContentChangeState($context, $pks, $value) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
if (! is_array($pks)) {
$pks = array($pks);
}
foreach ( $pks as $pk ) {
$this->dowork($this->model->getItem($pk), 'edit');
}
}
public function onContentAfterSave($context, $object, $isNew) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
$this->dowork($object, $isNew ? 'create' : 'edit');
}
private function dowork($object, $action) {
...
}
}
So I have a problem I have an array that is passes to setData function
after that I call getE that suppose to return the array but instead I'm getting Null what am I doing wrong?
<?php
class Se {
public $data1;
public function setData(array $data){
if (empty($data)) {
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
}
public function getE(){
return $data1[0];
}
}
$tmpaaa= array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
So my revised code looks like this now
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = $data;
}
public function getE()
{
return $this->$data1[0];
}
};
$tmpaaa= array('3','2');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
?>
In order to access class instance properties from within the class, you need to prefix the variable name with $this. See http://php.net/manual/language.oop5.properties.php
To fix your problem, change this in setData
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
to this
$this->data1 = array_values($data);
var_dump($this->data1);
and getE to
public function getE(){
return $this->data1[0];
}
Update
As it appears the $data1 property is required in Se, I'd set it in the constructor, eg
public function __construct(array $data) {
$this->setData($data);
}
and instantiate it with
$ttt = new Se($tmpaaa);
echo $ttt->getE();
It is also recommended not closing the php tag in a class file, this prevents space issues.
<?php
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = array_values($data); //you error was here, no need to to assign $data twice so I deleted top line.
}
public function getE()
{
return $this->data1[0];
}
}
$tmpaaa = array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
I want to retrieve data from my first form into my function executeAddDomaines to use these into a second form called by this function but when i give $form in parameters to this function i have this error :
Catchable fatal error: Argument 2 passed to domaineActions::executeAddDomaines() must be an instance of sfForm, none given, called in /home/webs/extranet100p100.net/htdocs/lib/vendor/symfony/lib/action/sfActions.class.php on line 60 and defined in /home/webs/extranet100p100.net/htdocs/apps/backend/modules/domaine/actions/actions.class.php on line 206
This is my code:
protected function processForm(sfWebRequest $request, sfForm $form)
{
$name = $form->getName();
$form->bind($request->getParameter($name), $request->getFiles($name));
if($form->isValid())
{
if($form->isNew())
{
$this->executeAddDomaines($request, $form);
$this->redirect('#add_domaines');
}
[...]
}
public function executeAddDomaines(sfWebRequest $request, sfForm $form)
{
$name = $form->getName();
$params = $request->getParameter($name);
$this->list_domaines = $params;
$this->form = new AddDomainesForm();
$this->setTemplate('listDomaines');
}
So how i can do it ?
Thank you :)
You can try to save the form data in session and then get it in the 2nd action.
Try this (i didn't test):
protected function processForm(sfWebRequest $request, sfForm $form)
{
$name = $form->getName();
$form->bind($request->getParameter($name), $request->getFiles($name));
if($form->isValid())
{
if($form->isNew())
{
# Replaced
$request->setAttribute("form", $form);
$this->redirect('#add_domaines');
}
[...]
}
public function executeAddDomaines(sfWebRequest $request)
{
# Added
$form = $request->getAttribute("form");
$name = $form->getName();
$params = $request->getParameter($name);
$this->list_domaines = $params;
$this->form = new AddDomainesForm();
$this->setTemplate('listDomaines');
}
After use it, you can clean the attribute form from the request
I am very new to cakePHP.
I am working on a controller like so:
class DesignersController extends AppController
{
var $name = 'Designers';
function index()
{
$data = $this->Designer->find('all');
$this->set('designers', $data);
}
function belle_etoile()
{
$this->show_designer("belle etoile");
}
function ritani()
{
$this->show_designer("ritani");
}
function swarovski()
{
$this->show_designer("swarovski");
}
function verragio()
{
$this->show_designer("verragio");
}
private function show_designer($designer)
{
$this->layout = 'first';
$data = $this->Designer->find('first', array('conditions' => array('Designer.name' => $designer)));
$this->set('data', $data);
$this->render('show_designer');
}
}
As you can see many of the "actions" are shortcuts for show_designer/param action where param is the name of the shortcut action.
Every one of these actions is a "designer" in the database. I just don't want to have to make the url designers/show_designer/ritani, I would rather it just be designers/ritani.
This works, but the problem is:
I have to create a bunch of redundant functions for every designer, and if a new designer gets added, it won't work until I add a function for it.
I would rather have a function/action that runs if the action requested is missing, and has the action that was requested as a parameter
so if I request url designers/stardust, since stardust is not defined as an action it would call the catch_all action with stardust as the parameter.
So instead of a bunch of redundant functions I could just have this:
function catch_all($action)
{
$this->show_designer($action)
}
Is there anyway to do something like this?
Use routing instead
// add this to app/config/routes.php
Router::connect('/designer/*', array('controller' => 'designers', 'action' => 'designer'));
In your controller
// and remove all actions 'belle_etoile', 'swarovski' etc
// change `show_designer` to `public designer`
class DesignersController extends AppController {
var $name = 'Designers';
function designer($name)
{
$this->layout = 'first';
$data = $this->Designer->find('first', array('conditions' => array('Designer.name' => $name)));
if(!empty($data)) {
$this->set('data', $data);
$this->render('show_designer');
} else {
$this->redirect('index');
}
}
}
have you tried adding a call method:
function __call($action,$params = array())
{
$this->show_designer($action)
}
Im not 100% shore how cake calls its methods but it should work:
Example of the usage:
finale class Test
{
function __call($action,$params = array())
{
echo $action . " called:<br />";
foreach($params as $param)
{
echo "Param: "$param . "<br />";
}
}
}
$test = new Test();
$test->SomeNonExistantmethod("param 1","param 2");
This would output:
SomeNonExistantmethod called:
param: param 1
param: param 2
your class would be like so:
class DesignersController extends AppController
{
var $name = 'Designers';
var $allowed = array(
"belle_etoile",
"ritani",
"swarovski",
"verragio"
);
function index()
{
$data = $this->Designer->find('all');
$this->set('designers', $data);
}
function __call($action,$params = array())
{
if(in_array($action,$this->allowed))
{
$this->show_designer($action);
}
}
private function show_designer($designer)
{
$this->layout = 'first';
$data = $this->Designer->find('first', array('conditions' => array('Designer.name' => $designer)));
$this->set('data', $data);
$this->render('show_designer');
}
}