I have a problem with making a page to allow people to edit their profile, the thing is that I have 3 form on one page (one for profile settings, second for social settings and the 3rd for the account settings) and I made 3 controllers to control each one, the problem is that I can't call 3 controllers at the same time for one route...
here is my profile.blade.php:
{!! Form::model($user, ['action' => ['ProfileController#updateProfile', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to edit username, name, description settings...
{!! Form:close() !!}
{!! Form::model($user, ['action' => ['ProfileController#updateSocial', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to set link to their social account...
{!! Form:close() !!}
{!! Form::model($user, ['action' => ['ProfileController#updateSettings', 'id' => $user->id], 'method' => 'PUT']) !!}
...Some input to update password or email...
{!! Form:close() !!}
Here is my web.php (routes):
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::put('/profile/{urlid}', 'ProfileController#updateProfile');
Route::put('/profile/{urlid}', 'ProfileController#updateSocial');
Route::put('/profile/{urlid}', 'ProfileController#updateSettings');
And here is my ProfileController:
public function updateProfile(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->fname=$request->input('fname');
$user->lname=$request->input('lname');
$user->profile_title=$request->input('profile_title');
$user->profile_resume=$request->input('profile_resume');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
public function updateSocial(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->perso_site=$request->input('perso_site');
$user->linkedin=$request->input('linkedin');
$user->twitter=$request->input('twitter');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
public function updateSettings(Request $request, $urlid)
{
$user = User::findOrFail($urlid);
$user->password=$request->input('password');
$user->email=$request->input('email');
$user->save();
return view('profile')->with([
'user' => $user
]);
}
The thing is that all of those 3 forms are on the same page, and I get an error If I call the 3 functions at the same time
I tried with only one function, it work, everything is ok but with one function, only one form is working, I hope I will find some help, It's been almost 2 hours that I'm blocked with this problem..
So in conclusion: I have 3 forms on the same page, I need these 3 functions to make them work, but I can't call 3 functions for only one route.
Seperate your url's and set your Routes like taht:
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::post('/profile/{urlid}', 'ProfileController#updateProfile')->name('update_profile');
Route::post('/profile/social/{urlid}', 'ProfileController#updateSocial')->name('update_social');
Route::post('/profile/settings/{urlid}', 'ProfileController#updateSettings')->name('update_settings');
and in the form blade use the route function for detting the action url like that ...
{!! Form::open(['url' => route('update_profile', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to edit username, name, description settings...
{!! Form:close() !!}
{!! Form::open(['url' => route('update_social', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to set link to their social account...
{!! Form:close() !!}
{!! Form::open(['url' => route('update_settings', ['urlid' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
...Some input to update password or email...
{!! Form:close() !!}
You route should looks like
Route::get('/profile/{urlid}', 'ProfileController#index')->name('profile');
Route::post('/profile/{profile_id}', 'ProfileController#updateProfile')->name('update_profile');
Route::post('/profile/{social_id}', 'ProfileController#updateSocial')->name('update_social');
Route::post('/profile/{settings_id}', 'ProfileController#updateSettings')->name('update_settings');
And your form in blade
{!! Form::open(['url' => route('update_profile', ['profile_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
{!! Form::open(['url' => route('update_social', ['social_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
{!! Form::open(['url' => route('update_settings', ['settings_id' => $user->id]), 'method' => 'post', 'files' => 'true', 'enctype' => "multipart/form-data"]) !!}
//....
{!! Form:close() !!}
In your function
public function updateProfile(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->fname=$data['fname'];
$user->lname=$data['lname']
$user->profile_title=$data['profile_title']
$user->profile_resume=$data['profile_resume']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
And the first form for you: https://pastebin.com/JznW20iy
Your second two form: https://pastebin.com/NuDTtvFR
and function
public function updateSocial(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->perso_site=$data['perso_site'];
$user->linkedin=$data['linkedin']
$user->twitter=$data['twitter']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
public function updateSettings(Request $request, $urlid)
{
$data = $request->all();
return $data; //check what you pass from the form...
//then after remove return
$user = User::findOrFail($urlid);
if($user)
{
$user->email=$data['email'];
$user->password=$data['newPass']
$user->update();
return view('profile')->with([
'user' => $user
]);
}
return "User not found";
}
Related
First issue is I have the following validators and public function in my table
UsersTable.php
$validator
->scalar('name')
->maxLength('name', 45)
->requirePresence('name', 'create')
->notEmptyString('name', 'You must enter a name for the user.');
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
public function checkExistingUser($value,$context)
{
return $this->find('all', ['conditions' => ['Users.name' => $context['data']['name'], 'Users.user_type_id' => $context['data']['user_type_id']]])->count() < 1 ;
}
When I save the form below I receive the message "Method checkExistingUser does not exist". Why doesn't it recognize the method when it's clearly defined in the table model? Am I missing something?
add.ctp
<?php echo $this->Form->create($user);?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->control('name', ['type' => 'text']);
echo $this->Form->control('user_type_id');
echo $this->Form->control('owner', array('type' => 'text', 'label' => "Owner Name"));
echo $this->Form->control('owner_contact', array('type' => 'text', 'label' => "Owner Contact (phone, email etc)"));
echo $this->Form->control('description', ['type' => 'textarea']);
echo $this->Form->control('ia_exception', array('type' => 'text', 'label' => "IA Exception Number"));
echo $this->Form->control('is_manual', array('type' => 'checkbox', 'label' => "Password Updated Manually"));
echo $this->Form->control('Environment', ['type' => 'select', 'multiple' => 'true', 'label' => 'Environment(s)']);
?>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->button('Save', ['type'=> 'submit', 'name' => 'submit']);
echo $this->Form->button('Cancel', ['type' => 'button', 'name'=>'cancel', 'onClick' => 'history.go(-1);return true;']);
echo $this->Form->end();
?>
</div>
UsersController.php
function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->set('The user has been saved');
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->set('The user could not be saved. Please, try again.');
}
}
$userTypes = $this->Users->UserTypes->find('list');
$changeSteps = $this->Users->ChangeSteps->find('list');
$environments = $this->Users->Environments->find('list');
$this->set(compact('user','userTypes', 'changeSteps', 'environments'));
}
Second issue is when I try to submit my form to check that the validator is working correctly for an empty name field I don't receive the message 'You must enter a name for the user'. Instead I receive a message stating 'This field is required'. Why is it not showing my message from notEmptyString? And where is 'This field is required' coming from?
For the first issue, I had to add a provider in my validator.
I changed
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
To this
$validator
->add('name', 'custom', ['rule' => 'checkExistingUser', 'provider' => 'table', 'message' => 'This user already appears to be in the system.', 'on' => 'create']);
Be careful with custom methods for validation during patching, because Cake expects string to be returned, otherwise it will rendere default meassage.
So for example, if we use a custom validation function during patching
// in a Controller
$this->Users->patchEntity($user, $data, ['validate' => 'custom');
Same applies for closures.
// in UserTable.php
public function validationCustom(Validator $validator) {
$validator = $this->validationDefault($validator);
$validator
->minLength('password',8,'At least 8 digits');
$validator->add('password',
'strength_light',[
'rule' => 'passwordCheck',
'provider' => 'table',
'message' => 'At least a number and a capital letter'
]
);
return $validator;
}
public function passwordCheck ($value = "") {
return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value);
}
This will return default message and not the custom one ("At least..") because we set a callable not-cakephp function as rule for custom validation, so the message should be returned by the called function:
public function passwordCheck ($value = "") {
if (!preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value))
return "At least a number and a capital letter";
}
I'm facing problem 'Class 'form' not found' I'm currently using laravel 5.4. I already have tried maximum efforts to solve.
Thanks
Error is : Whoops, looks like something went wrong.
1/1
FatalErrorException in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23:
Class 'Form' not found
in d0b19e04e5a1f8a5507d8ca427362b23807103ca.php line 23
Here is my Comp
{
"require": {
"php": ">=5.6.4",
"laravel/framework": "5.4.*",
"laravel/tinker": "~1.0",
"laravelcollective/html": "^5.4"
},
}
I run the composer update command.
Here is my app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
'Collective\Html\HtmlServiceProvider',
/*
* Package Service Providers...
*/
Laravel\Tinker\TinkerServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'FORM' => 'Collective\Html\FormFacade',
'HTML' => 'Collective\Html\HtmlFacade',
],
];
using form in formupload.blade.php
#if(isset($success))
<div class="alert alert-success"> {{$success}} </div>
#endif
{!! Form::open(['action'=>'ImageController#store', 'files'=>true]) !!}
<div class="form-group">
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Description:') !!}
{!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>5] ) !!}
</div>
<div class="form-group">
{!! Form::label('image', 'Choose an image') !!}
{!! Form::file('image') !!}
</div>
<div class="form-group">
{!! Form::submit('Save', array( 'class'=>'btn btn-danger form-control' )) !!}
</div>
{!! Form::close() !!}
<div class="alert-warning">
#foreach( $errors->all() as $error )
<br> {{ $error }}
#endforeach
</div>
</div>
Put this in composer.json
"require": {
"laravelcollective/html": "^5.4"
},
and Run
composer update
in command afterwards
Or
composer require laravelcollective/html
Then add this in your config/app.php in providers section array
Collective\Html\HtmlServiceProvider::class,
After that add two class aliases in the config/app.php in aliases array
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
Looks like you set the alias for your Form Class to "FORM" here in your app.php:
'FORM' => 'Collective\Html\FormFacade',
Try changing that to Form like so:
'Form' => 'Collective\Html\FormFacade',
then it should work
run command
composer require laravelcollective/html
when the composer update the require html laravel collective
then add these two line into config/app.php into the section of
'aliases' => [ ],
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
then add the line into config/app.php
'providers' => [ ], and save the file
Collective\Html\HtmlServiceProvider::class,
Run the command
composer require laravelcollective/html
add these two lines into config/app.php into the section of
'aliases' => [ ],
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
add the line into config/app.php
'providers' => [ ], and save the file
Collective\Html\HtmlServiceProvider::class,
this also works for 6.X
class aliases in the config/app.php
'Form' => 'Collective\Html\FormFacade',
this is working for me
I am creating a magento custom admin module and a form. I want update this form but not updating. In Controller, under SaveAction() I print $this->getRequest()->getPost() and get empty array. please help me. Below code for form declination..
protected function _prepareForm() {
$form = new Varien_Data_Form(array(
'id' => 'edit_form1',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
And Create a from filed set like
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('qbanner_form', array('legend' => Mage::helper('qbanner')->__('Art information')));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('catalog')->__('Product'),
'required' => false,
'name' => 'name',
));
$fieldset->addField('artist_name', 'text', array(
'label' => Mage::helper('catalog')->__('Artist Name'),
// 'name' => 'artist_name',
'value' => Mage::helper('catalog')->__('Art Name value'),
));
$fieldset->addField('bca_status', 'select', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'bca_status',
'values' =>$this->_getAttributeOptions('bca_status'),
));
$fieldset->addField('reason', 'editor', array(
'name' => 'reason',
'label' => Mage::helper('catalog')->__('Reason'),
'title' => Mage::helper('catalog')->__('Reason'),
'style' => 'width:440px; height:300px;',
'wysiwyg' => true,
'required' => false,
));
$fieldset->addField('thumbnail', 'text', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'thumbnail',
//'values' =>$this->_getAttributeOptions('thumbnail'),
//'renderer' => 'Qaz_Qbanner_Block_Adminhtml_Qbanner_Grid_Renderer_Image'
));
if (Mage::getSingleton('adminhtml/session')->getQbannerData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getQbannerData());
Mage::getSingleton('adminhtml/session')->setQbannerData(null);
} elseif (Mage::registry('qbanner_data')) {
$form->setValues(Mage::registry('qbanner_data')->getData());
}
return parent::_prepareForm();
}
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
Here my
SaveAction()
public function saveAction() {
echo print_r( $this->getRequest()->getPost());
}
I have tied verious post. Any ideas?
Common error for all. You just need to add form key to your form.
Just add this line below your form declaration.
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Like this
<form action="<?php echo Mage::helper("adminhtml")->getUrl("demo/adminhtml_demo/demo");?>" method="post" id="custom-payment-form" enctype="multipart/form-data">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Add this. Now you can get parameters by $this->getRequest()->getPost().
you can get variable of post and get method in magento with $this->getRequest()->getParams(); getParams() method But if you want to get exactly some variable data then use getParam('id');
/magento/catalog/product/view/id/406/category/14
$this->getRequest()->getParam('id') // 406
$this->getRequest()->getParams(); //get all get and post variables
I have two contact forms in my CakePHP application -- one with its own Controller, Model, and View, and another one in an element that can be accessed as a "quick" contact form from the footer of every page on the site.
The code for both forms is the same. The element is intended to access the Controller and Model that the other form uses. However, the element is not submitting the data or sending the email, while the regular page works just fine.
Here is the MVC Code for the regular form that IS working:
<!-- Model: Model/Contact.php -->
<?php
class Contact extends AppModel {
var $name = 'Contacts';
public $useTable = false; // Not using the database, of course.
var $validate = array(
'name' => array(
'rule' => '/.+/',
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'allowEmpty' => false,
'required' => true,
)
);
function schema() {
return array (
'name' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'email' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'message' => array('type' => 'text', 'length' => 2000, 'class' => 'contact input'),
);
}
}
?>
<!-- Controller: Controller/ContactsController.php -->
class ContactsController extends AppController
{
var $name = 'Contacts';
/* var $uses = 'Contact'; */
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
public function contact() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
// $this->redirect(array('controller' => 'pages', 'action' => 'index'));
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
}
?>
<!-- View: Views/Contacts/index.ctp -->
<?
$main = 'contact';
$title = 'quick contact';
?>
<div style="border-bottom: solid 1px #ccc;">
<h1 style="position:relative; float:left;"><?php echo $main; ?></h1>
<h2 style="position:relative;float:left;margin-top:15px; color: #869c38"> • <?php echo $title;?></h2>
<br><br>
</div>
<div class="clear"><br></div>
<div id="interior-page">
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
</div>
And here is the view for the quick contact form that is NOT working, located in an element displayed in the footer of the default layout:
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
I tried different ways of changing the form action, but I couldn't figure that out.
Usually, cake "automagically" creates the action of the form based on where you call it from E.g. if called from the view Views/Contacts/index.ctp, it will set the action to /contacts/index. In case of an element, Cake can't really guess what you're trying to do, so you need to set the action manually:
$this->Form->create('Contact', array('action' => 'index'));
Or set the full URL alternatively:
$this->Form->create('Contact', array('url' => '/contacts/index'));
Make sure you're including the Contact model for use on every page you need to create that form. In your case, since it's in your layout, that likely means you should put it in your AppController, so every page has access to it.
You also need to specify where the form should submit to:
echo $this->Form->create('Contact', array(
'url' => array('controller'=>'contacts', 'action'=>'contact')
)
);
Off-note - You can combine the last 2 lines:
echo $this->Form->end('Submit');
This creates the submit button with text "Submit" and also closes the form.
Thanks for this! It helped me a lot.
Just a quick thing, you're sending the email twice.
Once here:
$email->send($userMessage);
And again here:
if ($email->send($userMessage))
The first instance ($email->send($userMessage)) isn't necessary.
Cheers
I am setting up a zend form as:
class Application_Form_Ticket_Search extends Zend_Form
{
private $_itemList;
public function setItemList($itemList)
{
$this->_itemList[0] = 'Select Item'; // Default selected value
foreach($itemList AS $key => $value)
{
$this->_itemList[$value['REFERENCE']] = $value['DESCRIPTION'];
}
}
// Initializes search form
public function init()
{
// Settings POST type request
$this->setName('search')->setMethod('GET');
$this->addElement('select', 'item',
array( 'label' => 'Item',
'filters' => array('StringTrim'),
'multiOptions' => $this->_itemList
))->removeDecorator('HtmlTag');
$this->addElement('submit', 'search',
array( 'class' => 'btn btn-primary btn-small',
'label' => 'Search',
'style' => 'margin-left:70px;')
)->removeDecorator('HtmlTag');
}
}
and in controller passing form's select box listing as:
$searchForm = new Application_Form_Ticket_Search(array('itemList' => $itemList));
and populating values(after a search request was made) like :
$searchForm->populate($filters);
when I debug $filters array, output was:
array(1) { ["item"]=> string(36) "201031999999992010051000000170430719" }
now the issue is with HTML: I received an output as(when a value was selected in dropdown):
<select name="item" id="item">
<option value="0" label="Select Item">Select Item</option>
<option value="201031999999992010051000000170430719" label="ELITE FRT CHWG N/AV GUM ST 15CT" selected="selected">ELITE FRT CHWG N/AV GUM ST 15CT</option>
<option value="201031999999992010051000000170430869" label="Consolidator" selected="selected">Consolidator</option>
<option value="201031999999992010051100000170450719" label="DAVID PUMPKIN SEEDS" selected="selected">DAVID PUMPKIN SEEDS</option>
<option value="201031999999992010051100000170450739" label="Consolidator" selected="selected">Consolidator</option>
<option value="201031999999992010051000000170430809" label="GARDETTO ORIGINAL" selected="selected">GARDETTO ORIGINAL</option>
Now you can see that every value is selected in dropdown and I always get last selected value.
What I am doing wrong or what can be done for it?
Try:
class Application_Form_Ticket_Search extends Zend_Form
{
public function setItemList($itemList)
{
$items = array('Select Item');
foreach($itemList as $key => $value) {
$items[$value['REFERENCE']] = $value['DESCRIPTION'];
}
$this->getElement('item')->setMultiOptions($items);
}
// Initializes search form
public function init()
{
// Settings POST type request
$this->setName('search')->setMethod('GET');
$this->addElement('select', 'item',
array( 'label' => 'Item',
'filters' => array('StringTrim')
))->removeDecorator('HtmlTag');
$this->addElement('submit', 'search',
array( 'class' => 'btn btn-primary btn-small',
'label' => 'Search',
'style' => 'margin-left:70px;')
)->removeDecorator('HtmlTag');
}
}
$searchForm = new Application_Form_Ticket_Search();
$searchForm->setItemList(array('itemList' => $itemList));