is there a way to pass a URL variable to a form action? I've got it working on a user details form, but when I'm trying to do it with a user file upload it won't work.
As you will see below, I have a form and a save action for saving user details. That works fine.
When I try to pass the URL variable to the User File Upload form, it doesn't work. It says that I'm trying to get a value of a non-object.
// Get Client ID from URL Parameters
public function getUser() {
if( isset($this->urlParams['ID']) && is_numeric($this->urlParams['ID']) ) {
return $user = Member::get()->byID($this->urlParams['ID']);
} else {
return $user = $this->request->postVars();
}
}
// Edit/Save a User's details
public function EditUserDetails() {
//Include JS for updating details
Requirements::javascript('module-memberprofiles/javascript/MemberProfileUpdate.js');
Requirements::set_force_js_to_bottom(true);
$fields = new FieldList(
$leftCol = CompositeField::create(
TextField::create('FirstName', 'First Name')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Surname', 'Surname')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
CompositeField::create(
TextField::create('Address', ''),
TextField::create('Suburb', ''),
CompositeField::create(
DropdownField::create('State', '', singleton('Member')->dbObject('State')->enumValues())->setFieldHolderTemplate('UserDetails_StatePostCode'),
TextField::create('PostCode', '')->setFieldHolderTemplate('UserDetails_StatePostCode')
)->addExtraClass('row')
)
->addExtraClass('userdetails-address wrap')
->setFieldHolderTemplate('UserDetails_AddressHolder'),
TextField::create('Phone', 'Phone')
->setFieldHolderTemplate('UserDetails_FieldHolder'),
TextField::create('Email', 'Email')
->setFieldHolderTemplate('UserDetails_FieldHolder')
)->setFieldHolderTemplate('UserDetails_CompositeField')
);
$actions = new FieldList(new FormAction('SaveUserDetails', 'Save Profile'));
$validation = new RequiredFields(array('FirstName','Surname','Email'));
$form = new Form ( $this, 'EditUserDetails', $fields, $actions, $validation);
$form->loadDataFrom($this->getUser());
$form->setTemplate('MemberProfilePage_UserDetailsForm');
return $form;
}
public function SaveUserDetails($data, $form) {
$table = Member::get()->byID($this->getUser());
$members = Member::get();
$emailExists = $members->filter(array(
'Email' => $data['Email'],
'ID:not' => $table->ID
));
if( $emailExists->count() > 0 ) {
$form->sessionMessage('Sorry, that email address already exists. Please try again','bad');
return $this->redirectBack();
} else {
$form->sessionMessage('You have successfully updated this user\'s details.','good');
}
$form->saveInto($table);
$table->write();
$this->redirectBack();
return $this;
}
//User file upload function
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files')
);
$actions = FieldList::create(FormAction::create('SaveUserFile', 'Upload files'));
$form = Form::create($this, __FUNCTION__, $fields, $actions, null);
$form->loadDataFrom($this->getUser());
return $form;
}
//Refresh files function
public function SaveUserFile($data, $form) {
$up = new Upload();
$file = Object::create('File');
$file->setFileName('newname');
$up->loadIntoFile($data['UserFiles'], $file, 'User-Files');
if($up->isError()) {
//handle error here
//var_dump($up->getErrors());
}else {
//file uploaded
//$file->OwnerID = 3;
//$file->write();
//$this->redirectBack();
return $this;
}
}
OK, I managed to figure this one out...
I had to set a form action to direct the upload function to the correct URL. It appears that the ID was being removed from the URL when I clicked submit, so the "getUser" function couldn't see the value.
Here's the working code for the Upload Form function:
public function UploadUserFile() {
$fields = FieldList::create(
FileField::create('UserFiles', 'Upload files'),
HiddenField::create('ID','',$this->getUser()->ID)
);
$actions = FieldList::create(
FormAction::create('SaveUserFile', 'Upload files')
->addExtraClass('button rounded solid')
);
$form = Form::create($this, 'UploadUserFile', $fields, $actions);
$form->setFormAction($this->Link().'UploadUserFile/'.$this->getUser()->ID);
return $form;
}
Related
I created a form and passed the values for name and picture from the form. The value is accessed from the Upload controller as follows:
$data = array(
'title' => $this->input->post('title', true),
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
return $data;
I need to pass these values to the view so, I modified the above code as:
class Upload extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function input_values(){
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data); }
function add(){
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
//logo image upload
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
}
But I am able to get only the value of title. Following error occurs for both name and title:
Message: Undefined variable: name
I have accessed the variables from the view as follows:
<?php var_dump($title)?>
<?php var_dump($name)?
<?php var_dump($picture)?>
so, this part is where you get the post data and load view (contain the upload form)
public function input_values() {
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data);
}
then this part is handle the post request from the upload form:
function add() {
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
and this part is where you upload the file
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
when you call add() function, it call input_values() function then load views then the next line of codes won't be executed (cmiiw).
so, maybe you want to change with this :
public function index() {
if ($this->input->post()) {
// then handle the post data and files tobe upload here
// save the post data to $data, so you will able to display them in view
} else {
// set the default data for the form
// or just an empty array()
$data = array();
}
// if the request was not a post, render view that contain form to upload file
$this->load->view('nameOfTheView', $data);
}
I wish to create the edit form in Silverstripe 4.2, much like this Stack Overflow's edit function that i'm looking for.
EDITED: I want to be able to have a page that is only available to the registered member of my website that they can post their class listings on the Frontend (not in CMS) as an owner, and need to have a 'edit' click that takes you to an identical form (same ClassListingForm) that lets member owner to edit/update their own class listings that they have posted. I have everything working except the edit and submit functions which I'm stuck on at the moment.
I have a link for editing the specific class listing:
Edit class listing</div>
It does redirected to 404 page not found with this url shown:
"http://.../learners/class-listings/edit/61"
Here's the code below I have so far, the ClassListingForm is working fine, just need to get the EditListingForm and doClassListing functions to work properly, and i may be doing something wrong in these codes? or is there a better way of doing the edit form properly which i'm unable to find anywhere on the search for specific on what i need as there's not much tutorial that covers the EditForm function on the SilverStripe lessons.
<?php
class ClassListings extends DataObject {
private static $table_name = 'ClassListings';
private static $db = [
'CourseTitle' => 'Varchar(255)',
'CourseLocation' => 'Varchar(255)',
];
private static $has_one = [
'ClassListingPage' => ClassListingPage::class,
];
}
<?php
class ClassListingPageController extends PageController {
private static $allowed_actions = [
'ClassListingForm',
'ClassEditForm'
];
public function ClassListingForm() {
$id = (int)$this->urlParams['ID'];
$data = ($id)? $data = ClassListings::get()->byID($id) : false;
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField'),
HiddenField::create('ID', 'ID')->setValue($ClassListingPageID)
),
FieldList::create(
FormAction::create('handleClassListing')
->setTitle('Post your class listing')
->addExtraClass('btn btn-primary primary')
),
RequiredFields::create(
'CourseTitle',
'CourseLocation'
)
);
$form->loadDataFrom(Member::get()->byID(Member::currentUserID()));
$form->getSecurityToken()->getValue();
if ($form->hasExtension('FormSpamProtectionExtension')) {
$form->enableSpamProtection();
}
$data = $this->getRequest()->getSession()->get("FormData.{$form->getName()}.data");
return $data ? $form->loadDataFrom($data) : $form;
}
public function handleClassListing($data, $form) {
$session = $this->getRequest()->getSession();
$session->set("FormData.{$form->getName()}.data", $data);
$class = ClassListings::create($this->owner);
$class->CourseTitle = $data['CourseTitle'];
$class->CourseLocation = $data['CourseLocation'];
$class->ID = $data['ID'];
$class->ClassListingPageID = $this->ID;
$form->saveInto($class);
$class->write();
$session->clear("FormData.{$form->getName()}.data");
$form->sessionMessage('Your class listing has been posted!','good');
$session = $this->getRequest()->getSession();
return $this->redirect($this->Link());
}
public function ClassEditForm() {
$ClassListingPageID = (int)$this->urlParams['ID'];
$data = ($ClassListingPageID)? $data = ClassListings::get()->byID($ClassListingPageID) : false;
$var = $this->getRequest()->getVar('$data');
if($var){
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField'),
HiddenField::create('ID', 'ID')->setValue($ClassListingPageID)
),
FieldList::create(
FormAction::create('doClassListing')
->setTitle('Post your class listing')
->addExtraClass('btn btn-primary primary')
),
RequiredFields::create(
'CourseTitle',
'CourseLocation',
)
);
$form->loadDataFrom(ClassListings::get()->filter(['ClassListingPageID' => $var])[0]);
$form->getSecurityToken()->getValue();
if ($form->hasExtension('FormSpamProtectionExtension')) {
$form->enableSpamProtection();
}
$data = $this->getRequest()->getSession()->get("FormData.{$form->getName()}.data");
return $data ? $form->loadDataFrom($data) : $form;
}
return;
}
public function doUpdateClassListing($data, Form $form) {
$session = $this->getRequest()->getSession();
$session->set("FormData.{$form->getName()}.data", $data);
$class = ClassListings::create($this->owner);
$class->CourseTitle = $data['CourseTitle'];
$class->CourseLocation = $data['CourseLocation'];
$class->ID = $data['ID'];
$class->ClassListingPageID = $this->ID;
$form->saveInto($class);
$class->write();
$session->clear("FormData.{$form->getName()}.data");
$form->sessionMessage('Your class listing has been updated!','good');
$session = $this->getRequest()->getSession();
return $this->redirect($this->Link());
}
}
Thought i post this answer to share in case if others have the same issue i had.
Finally got it working and solved the issue now, have replaced whole the codes for both ClassEditForm and doUpdateClassListing methods, and also created another funcation called Edit:
public function Edit(HTTPRequest $request) {
$id = (int)$request->param('ID');
$class = ClassListings::get()->byID($id);
if (!$class || !$class->exists()) {
return ErrorPage::response_for(404);
}
$form = $this->ClassEditForm($class);
$return = $this->customise(array(
'Title' => 'Edit: ' . $class->CourseTitle,
'Form' => $form,
));
return $return = $return->renderWith(array('ClassListingPage_edit', 'Page'));
}
public function ClassEditForm() {
$id = (int)$this->urlParams['ID'];
$class = ClassListings::get()->byID($id);
$fields = new FieldList(
HiddenField::create('ID')->setValue($id),
TextField::create('CourseTitle', 'Course title:')
->setAttribute('placeholder', 'NZSL Level 1, NZSL 1A')
->setCustomValidationMessage('Please enter the course title field')
->addExtraClass('requiredField CourseTitle'),
TextField::create('CourseLocation','Region:')
->setAttribute('placeholder', 'Enter region')
->setCustomValidationMessage('Please enter the region field')
->addExtraClass('requiredField')
);
$actions = new FieldList(
FormAction::create('doUpdateClassListing')
->setTitle('Update your class listing')
->addExtraClass('btn btn-primary primary')
);
$validator = new RequiredFields([
'CourseTitle',
'CourseLocation'
]);
$form = Form::create($this, 'ClassEditForm', $fields, $actions, $validator);
if ($class) $form->loadDataFrom($class);
return $form;
}
public function doUpdateClassListing($data, Form $form) {
if($data['ID']){
$id = $data['ID'];
$class = ClassListings::get()->byID($id);
} else {
$class = ClassListings::create();
}
$form->saveInto($class);
$id = $class->write();
$form->sessionMessage('Your class listing has been updated!','good');
$this->redirect($this->Link() . "edit/".$id);
}
I want to add some fields by default using Userforms plugin in Silverstripe 3.2
I think i found the function which adds fields when the 'Add Field' button is pressed in Gridfield, but i`m not sure and i don't know how to adda formfield type (Date input) by calling a simple function.
Here is the full function:
public function getFieldEditorGrid() {
Requirements::javascript(USERFORMS_DIR . '/javascript/FieldEditor.js');
$fields = $this->owner->Fields();
$this->createInitialFormStep(true);
$editableColumns = new GridFieldEditableColumns();
$fieldClasses = singleton('EditableFormField')->getEditableFieldClasses();
$editableColumns->setDisplayFields(array(
'ClassName' => function($record, $column, $grid) use ($fieldClasses) {
if($record instanceof EditableFormField) {
return $record->getInlineClassnameField($column, $fieldClasses);
}
},
'Title' => function($record, $column, $grid) {
if($record instanceof EditableFormField) {
return $record->getInlineTitleField($column);
}
}
));
$config = GridFieldConfig::create()
->addComponents(
$editableColumns,
new GridFieldButtonRow(),
GridFieldAddClassesButton::create('EditableTextField')
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD', 'Add Field'))
->setButtonClass('ss-ui-action-constructive'),
GridFieldAddClassesButton::create('EditableFormStep')
->setButtonName(_t('UserFormFieldEditorExtension.ADD_PAGE_BREAK', 'Add Page Break')),
GridFieldAddClassesButton::create(array('EditableFieldGroup', 'EditableFieldGroupEnd'))
->setButtonName(_t('UserFormFieldEditorExtension.ADD_FIELD_GROUP', 'Add Field Group')),
new GridFieldEditButton(),
new GridFieldDeleteAction(),
new GridFieldToolbarHeader(),
new GridFieldOrderableRows('Sort'),
new GridFieldDetailForm()
);
$fieldEditor = GridField::create(
'Fields',
_t('UserDefinedForm.FIELDS', 'Fields'),
$fields,
$config
)->addExtraClass('uf-field-editor');
return $fieldEditor;
}
We can call onAfterWrite to set default fields after the page is saved for the first time.
class CustomFormPage extends UserDefinedForm {
public function onAfterWrite() {
if (!$this->Fields() || !$this->Fields()->exists()) {
$nameField = new EditableTextField();
$nameField->Name = 'Name';
$nameField->Title = 'Name';
$nameField->ParentID = $this->ID;
$nameField->Required = true;
$nameField->CustomErrorMessage = 'Please enter your name.';
$nameField->write();
$dateField = new EditableDateField();
$dateField->Name = 'Date';
$dateField->Title = 'Date';
$dateField->ParentID = $this->ID;
$dateField->Required = true;
$dateField->CustomErrorMessage = 'Please enter this date.';
$dateField->write();
}
parent::onAfterWrite();
}
}
Hi I am creating an application using laravel and i have a model where asset_number field is unique and the validation rules are as follows
MODEL
protected $rules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{id}',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
Here is my controller code for create and edit
CONTROLLER
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new Assetdetail instance
$assetdetail = new Assetdetail();
// attempt validation
if ($assetdetail->validate($new))
{
// Save the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function getEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
//$assetlife = DB::table('asset_details')->where('id', '=', $assetdetailId)->lists('asset_life');
$location_list = array('' => '') + Location::lists('name', 'id');
$assettype_list = array('' => '') + Assettype::lists('asset_type', 'id');
$assignTo_list = array('' => 'Select a User') + User::select(DB::raw('CONCAT(first_name, " ", last_name) AS full_name'), 'id') ->lists('full_name', 'id');
$assetdetail_options = array('' => 'Top Level') + DB::table('asset_details')->where('id', '!=', $assetdetailId)->lists('asset_number', 'id');
return View::make('backend/assetdetails/edit', compact('assetdetail'))->with('assetdetail_options',$assetdetail_options)->with('location_list',$location_list)->with('assettype_list',$assettype_list)->with('assignTo_list',$assignTo_list);
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
$new = Input::all();
/*if ($assetdetail ->asset_number == Input::old('asset_number') &&
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
}*/
if ($assetdetail->validate($new))
{
// Update the asset data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
My Route.php
Route::post('create', array('as' => 'savenew/assetdetail','uses' => 'Controllers\Admin\AssetdetailsController#postCreate'));
Route::get('{assetdetailId}/edit', array('as' => 'update/assetdetail', 'uses' => 'Controllers\Admin\AssetdetailsController#getEdit'));
Route::post('{assetdetailId}/edit', 'Controllers\Admin\AssetdetailsController#postEdit');
Now the problem is whenever i try to update my form my asset_number field throws an Error: The asset_number has already been taken.How do i pass the id in my controller while updating my form so that it throws error only if an already existing asset_number is used and not while editing the form with current asset_number.
I tried the following with no luck
Model
'asset_number' => 'mobileNumber' => 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Controller
Assetdetail::$rules['mobileNumber'] = 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Hi i finally found a working solution myself here is what i did please take a look
Controller
class AssetdetailsController extends AdminController
{
protected $validationRules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
public function postCreate()
{
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// attempt validation
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.assetdetail_not_exist'));
}
$this->validationRules['asset_number'] = "required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{$assetdetail->asset_number},asset_number";
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
}
I have file (ProfileController.php) which contains the following code:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'names' => $result->names,
// 'password' => $result->password,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'names' => $form->getValue("names"),
'password' => $form->getValue("password"),
);
$form->populate($data->toArray());
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
and another file (edit.phtml) with following code:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
?>
I would like the users to be able to edit their Username and password. How do I go about it?
First: move the Zend_Auth stuff up to init() or preDispatch(), that way Auth will run against any or all actions in the controller.
The trick in getting more then one submit button to work is to give the buttons different names so that getParam('') has something to work with.
Normally I only do this sort of thing when doing deletes, for edit's or update's I just submit the whole array back to the database. I typically use the Zend_Db_Table_Row save() method instead of Zend_Db_Table's insert() or update() so the mechanism is a little different.
I just use a simple form to perform an update, here is the controller code (the view just echo's the form):
//update album information
public function updatealbumAction()
{ //get page number from session
$session = new Zend_Session_Namespace('page');
//get album id
$id = $this->getRequest()->getParam('id');
$model = new Music_Model_Mapper_Album();
//fetch the album database record
$album = $model->findById($id);
$form = new Admin_Form_Album();
//this form is used elsewhere so set the form action to this action
$form->setAction('/admin/music/updatealbum/');
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();//get valid and filtered form values
$newAlbum = new Music_Model_Album($data);//create new entity object
$update = $model->saveAlbum($newAlbum);//save/update album info
$this->message->addMessage("Update of Album '$update->name' complete!");//generate flash message
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));//redirect back to the page the request came from
}
} else {
$form->populate($album->toArray());
$this->view->form = $form;
}
}
This is a pretty common update action.
Now here is how you might use different request parameters to perform an action on a record. I use this to delete database records but anything is possible.
public function deleteAction()
{
$session = new Zend_Session_Namespace('page');
$request = $this->getRequest()->getParams();
try {
switch ($request) {
//if
case isset($request['trackId']):
$id = $request['trackId'];
$model = new Music_Model_Mapper_Track();
$model->deleteTrack($id);
$this->message->addMessage("Track Deleted!");
break;
case isset($request['albumId']):
$id = $request['albumId'];
$model = new Music_Model_Mapper_Album();
$model->deletealbum($id);
$this->message->addMessage("Album Deleted!");
break;
case isset($request['artistId']):
$id = $request['artistId'];
$model = new Music_Model_Mapper_Artist();
$model->deleteArtist($id);
$this->message->addMessage("Artist Deleted!");
break;
default:
break;
}
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
} catch (Exception $e) {
$this->message->addMessage($e->getMessage());
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
}
you can pass the request parameters as submit button labels or as urls or whatever works for you.
Good Luck!