public function saveAction() { $this->getRequest()->isPost(); $this->buildForm("admin/group/save"); if ($this->gForm->isValid($_POST)) { $values = $this->gForm->getValues(); } //Build Group Object $group = new Group(); //Upload Logo if (copy($values['logo'], Zend_Registry::get('config')->files->logo->dir . DIRECTORY_SEPARATOR . basename($values['logo']))) { $values['logo'] = Zend_Registry::get('config')->files->logo->dir . "/" . basename($values['logo']); } //Convert polygon cordenates preg_match_all("/\\(([0-9\\.\\,\\-\\s]*)\\)[\\,]?/", $values['area_coords'], $rawcoords); foreach ($rawcoords[1] as $coord) { $cvalues = explode(",", $coord); $cobj = new stdClass(); $cobj->lat = trim($cvalues[0]); $cobj->lng = trim($cvalues[1]); $coords[] = $cobj; } $values['area_coords'] = json_encode($coords); //Register Administrators $admins = explode(",", $values['admins']); foreach ($admins as $adm) { if ($adm != "") { $group->Admins[]->user_id = $adm; } } //Go through Activity Types $actvTypes = Doctrine_Query::create()->from('ActivityType')->orderBy("weight")->execute(); foreach ($actvTypes as $atype) { $atype_key = "atype_" . $atype->atype; $aSource = new ActivitySource(); $aSource->atype = $atype->atype; $aSource->target = $values[$atype_key]; $group->ActivitySources[] = $aSource; } //populate group $group->fromArray($values); //Save Group $group->save(); var_dump($values, $group->toArray()); //Grab pre-saved venues and tie group_id $venues = Doctrine_Query::create()->from('Venue')->where("Venue.name LIKE ?", array($values['tmp_id'] . '%'))->execute(); foreach ($venues as $venue) { $venue->name = str_replace($values['tmp_id'] . "_", "", $venue->name); $venue->group_id = $group->id; $venue->save(); } $this->_helper->flashMessenger("Group added!"); //$this->_helper->redirector('index'); $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); }
/** * Hook for node save - save parent (category) * * @param Zend_Form $form * @param array $arguments */ public function nodeSave(&$form, &$arguments) { $item = array_shift($arguments); $arguments = $form->getValues(); if (isset($arguments['rewrite_path'])) { $router = Zend_Controller_Front::getInstance()->getRouter(); $default_url = $router->assemble(array('id' => $item->id), $item->type); $factory = new Rewrite_Path_Factory(); $path = $factory->find($item->id)->current(); if ($arguments['rewrite_path'] == $default_url) { if ($path) { $path->delete(); } } else { if (!$path) { $path = $factory->createRow(); $path->nid = $item->id; } if ($arguments['rewrite_path'] != $path->path) { $path->path = $arguments['rewrite_path']; $path->save(); } } } }
public function detailAction() { $newsUrl = $this->getRequest()->getParam('url', null); try { $news = $this->newsRepository->fetchEntityByUrl($newsUrl); } catch (\Exception $e) { throw new \Exception($e->getMessage(), 404); } $this->view->headTitle($news->headline); $this->view->headMeta()->setName('description', $this->_helper->truncate($news->content, 255)); $configForm = $this->getInvokeArg('bootstrap')->getResource('configForm'); $commentForm = new \Zend_Form($configForm->comment); if ($this->getRequest()->isPost()) { if ($commentForm->isValid($_POST)) { try { $values = $commentForm->getValues(); unset($values['csrf']); unset($values['firstname']); # SpamDetection $values['news'] = $news; $this->commentRepository->saveEntity($values); $commentForm->reset(); #$this->_helper->systemMessages('notice', 'Kommentar erfolgreich gespeichert'); } catch (\Exception $e) { $log = $this->getInvokeArg('bootstrap')->log; $log->log($e->getMessage(), \Zend_Log::ERR, array('trace' => $e->getTraceAsString())); #$this->_helper->systemMessages('error', 'Kommentar konnte nicht gespeichert werden'); } } } $commentForm->setAction('/news/' . $newsUrl); $this->view->form = $commentForm; $this->view->news = $news; }
public function getValues($supress = FALSE) { $data = parent::getValues($supress); if (NULL === $this->_object) { return $data; } try { $this->_object->setFromArray($data); return $this->_object; } catch (App_Class_Exception_FieldValidate $e) { $field = $e->getField(); //field que deu erro na validação $message = $e->getMessage(); //mensagem de erro //se exitir o campo no form if (isset($this->_elements[$field])) { $element = $this->_elements[$field]; /* @var $element Zend_Form_Element_Xhtml */ $element->addError($message); //adiciona um erro de validação no campo com a mensagem gerada na exception } else { $this->addError($message); } } catch (Exception $e) { $this->addError($e->getMessage()); } return FALSE; }
public function editAction() { $configForm = $this->getInvokeArg('bootstrap')->getResource('configForm'); $userForm = new Zend_Form($configForm->user); $userId = $this->getRequest()->getParam('id', null); if ($this->getRequest()->isPost()) { if ($userForm->isValid($_POST)) { try { $values = $userForm->getValues(); unset($values['password_repeat']); $userId = $this->userRepository->saveEntity($values); $this->_helper->systemMessages('notice', 'Nutzer erfolgreich gespeichert'); } catch (\Exception $e) { $log = $this->getInvokeArg('bootstrap')->log; $log->log($e->getMessage(), \Zend_Log::ERR, array('trace' => $e->getTraceAsString())); $this->_helper->systemMessages('error', 'Nutzer konnte nicht gespeichert werden'); } } } else { try { $entity = $this->userRepository->fetchEntity($userId); $userForm->populate($entity->toArray()); } catch (\Exception $e) { throw new \Exception($e->getMessage(), 404); } } $userForm->setAction('/admin/user/edit/' . $userId); $this->view->form = $userForm; }
/** * Override to unset automatically added security fields * * @param bool $suppressArrayNotation * @return array */ public function getValues($suppressArrayNotation = false) { $values = parent::getValues($suppressArrayNotation); unset($values[self::HONEYPOT_FIELD_KEY]); unset($values[self::TIMESTAMP_FIELD_KEY]); return $values; }
public function saveFormData(Zend_Form $form) { $item = $this->_model; $item->setOptions($form->getValues()); if ($this->_request->getParam('contentMarkdown')) { $context_html = Michelf\MarkdownExtra::defaultTransform($this->_request->getParam('contentMarkdown')); $item->setContentHtml($context_html); } $fullPath = $this->_request->getParam('path'); if ($this->_request->getParam('parentId') != 0) { $parentCategory = $this->_modelMapper->find($this->_request->getParam('parentId'), new Pipeline_Model_PipelineCategories()); if ($parentCategory) { $fullPath = $parentCategory->getFullPath(); } } $item->setFullPath($fullPath); $this->setMetaData($item); $this->getModelMapper()->save($item); if ($item->getId() && $item->getId() != '') { $id = $item->getId(); } else { $id = $this->getModelMapper()->getDbTable()->getAdapter()->lastInsertId(); } $item = $this->getModelMapper()->find($id, $this->getModel()); foreach ($form->getElements() as $key => $element) { if ($element instanceof Zend_Form_Element_File && $element->isUploaded()) { $item = $this->saveUploadFile($element, $item); } } return $item; }
/** * Get calculated form values * * Note: strips off input named 'submit' * * @return array */ public function getValues($suppressArrayNotation = false) { $values = parent::getValues(); if (isset($values['submit'])) { unset($values['submit']); } return $values; }
private function saveComment(Zend_Form $form, GC\Entity\BlogEntry $blogEntry) { $comment = new GC\Entity\Comment($form->getValues()); $comment->blogEntry = $blogEntry; $this->_em->persist($comment); $this->_em->flush(); // clear form values $form->populate(array('name' => '', 'email' => '', 'content' => '')); }
protected function _save(Zend_Form $form, array $info, $defaults = array()) { if (!$form->isValid($info)) { return false; } $data = $form->getValues(); if (array_key_exists('passwd', $data) && '' != $data['passwd']) { } }
/** * Hook for node save - if type is Comments Node, save extra fields * * @param Zend_Form $form * @param array $arguments */ public function nodeSave(&$form, &$arguments) { $item = array_shift($arguments); $arguments = $form->getValues(); if ($item->type == "comments_node") { $item->pid = $arguments['pid']; $item->save(); Zoo::getService('cache')->remove("Comments_Block_List_" . $item->pid); } }
private function save(Zend_Form $form) { $id = (int) $form->getValue('id'); $category = new GC\Entity\Category(array('id' => $id)); if ($id != 0) { $category = $this->_em->find('GC\\Entity\\Category', $id); } $category->populate($form->getValues()); $this->_em->getRepository('GC\\Entity\\Category')->save($category); }
public function testPopulateProxiesToSetDefaults() { $this->testCanAddAndRetrieveMultipleElements(); $values = array('foo' => 'foovalue', 'bar' => 'barvalue', 'baz' => 'bazvalue', 'bat' => 'batvalue'); $this->form->populate($values); $test = $this->form->getValues(); $elements = $this->form->getElements(); foreach (array_keys($values) as $name) { $this->assertEquals($values[$name], $test[$name]); } }
public function contactFormAction() { //create the form $form = new Zend_Form(); //this page should post back to itself $form->setAction($_SERVER['REQUEST_URI']); $form->setMethod('post'); $name = $form->createElement('text', 'name'); $name->setLabel($this->view->getTranslation('Your Name') . ': '); $name->setRequired(TRUE); $name->addFilter('StripTags'); $name->addErrorMessage($this->view->getTranslation('Your name is required!')); $name->setAttrib('size', 30); $email = $form->createElement('text', 'email'); $email->setLabel($this->view->getTranslation('Your Email') . ': '); $email->setRequired(TRUE); $email->addValidator('EmailAddress'); $email->addErrorMessage($this->view->getTranslation('Invalid email address!')); $email->setAttrib('size', 30); $subject = $form->createElement('text', 'subject'); $subject->setLabel($this->view->getTranslation('Subject') . ': '); $subject->setRequired(TRUE); $subject->addFilter('StripTags'); $subject->addErrorMessage($this->view->getTranslation('The subject is required!')); $subject->setAttrib('size', 40); $message = $form->createElement('textarea', 'message'); $message->setLabel($this->view->getTranslation('Message') . ': '); $message->setRequired(TRUE); $message->addErrorMessage($this->view->getTranslation('The message is required!')); $message->setAttrib('cols', 35); $message->setAttrib('rows', 10); $captcha = new Zend_Form_Element_Captcha('captcha', array('label' => $this->view->getTranslation('Please verify you\'re a human'), 'captcha' => array('captcha' => 'Figlet', 'wordLen' => 6, 'timeout' => 300))); $form->addElement($name); $form->addElement($email); $form->addElement($subject); $form->addElement($message); $form->addElement($captcha); $form->addElement('submit', 'submitContactForm', array('label' => $this->view->getTranslation('Send Message'))); $this->view->form = $form; if ($this->_request->isPost() && Digitalus_Filter_Post::has('submitContactForm')) { if ($form->isValid($_POST)) { //get form data $data = $form->getValues(); //get the module data $module = new Digitalus_Module(); $moduleData = $module->getData(); //render the message $this->view->data = $data; $htmlMessage = $this->view->render('public/message.phtml'); $mail = new Digitalus_Mail(); $this->view->isSent = $mail->send($moduleData->email, array($data['email'], $data['name']), $data['subject'], $htmlMessage); } } }
/** * Retrieve all form element values * * @param bool $suppressArrayNotation * @param array $omit list of fields to ommit (usually submit, and token) * @return array */ public function getValues($suppressArrayNotation = false, $omit = array('submit', 'hash')) { $return = parent::getValues($suppressArrayNotation); if (is_array($omit)) { foreach ($omit as $key) { if (!array_key_exists($key, $return)) { continue; } unset($return[$key]); } } return $return; }
public function getValues($suppressArrayNotation = false) { $values = parent::getValues($suppressArrayNotation); $tags = array(); foreach ($values as $key => $value) { if (preg_match('~^tag_(\\d+)$~', $key, $matches)) { if ($value == 1) { $tags[] = $this->_tagRepository->fetchEntity($matches[1]); } unset($values[$key]); } } $values['tags'] = $tags; return $values; }
public function indexAction() { $session = new \Zend_Session_Namespace('twitter', true); $oauthConfig = array('callbackUrl' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], 'siteUrl' => 'http://twitter.com/oauth'); $configForm = $this->getInvokeArg('bootstrap')->getResource('configForm'); $twitterApiForm = new \Zend_Form($configForm->twitterApi); if ($this->getRequest()->isPost()) { if ($twitterApiForm->isValid($_POST)) { try { $this->twitterRepository->saveEntity($twitterApiForm->getValues()); $oauthConfig['consumerKey'] = $twitterApiForm->getValue('consumerKey'); $oauthConfig['consumerSecret'] = $twitterApiForm->getValue('consumerSecret'); $consumer = new \Zend_Oauth_Consumer($oauthConfig); $token = $consumer->getRequestToken(); $session->twitterRequestToken = serialize($token); $consumer->redirect(); } catch (\Exception $e) { $log = $this->getInvokeArg('bootstrap')->log; $log->log($e->getMessage(), \Zend_Log::ERR, array('trace' => $e->getTraceAsString())); $this->_helper->systemMessages('error', 'Einstellungen konnte nicht gespeichert werden'); } } } else { try { $entity = $this->twitterRepository->fetchEntity(); if ($entity) { if (isset($session->twitterRequestToken)) { $oauthConfig['consumerKey'] = $entity->consumerKey; $oauthConfig['consumerSecret'] = $entity->consumerSecret; $consumer = new \Zend_Oauth_Consumer($oauthConfig); $token = $consumer->getAccessToken($_GET, unserialize($session->twitterRequestToken)); $this->twitterRepository->saveEntity(array('accessToken' => serialize($token))); unset($session->twitterRequestToken); $this->_helper->systemMessages('notice', 'Einstellungen erfolgreich gespeichert'); } $twitterApiForm->populate($entity->toArray()); } } catch (\Exception $e) { $log = $this->getInvokeArg('bootstrap')->log; $log->log($e->getMessage(), \Zend_Log::ERR, array('trace' => $e->getTraceAsString())); $this->_helper->systemMessages('error', 'Einstellungen konnte nicht gespeichert werden'); } } $twitterApiForm->setAction('/admin/twitter'); $this->view->form = $twitterApiForm; }
/** * Zend_Form doesn't support numeric subform (and element) names. * Because of that getValues() returns numeric array-keys instead of * the timestamps that are supplied in setDefaults(). * This wacky fix determines if indexed arrays are present and if so, * translates those back to the keys originally passed in. * * getValue(timestamp) works correct and doesn't need to be changed. * * http://framework.zend.com/issues/browse/ZF-4204 * * @param boolean $suppressArrayNotation * @return array */ public function getValues($suppressArrayNotation = false) { $formValues = parent::getValues($suppressArrayNotation); $keys = array_keys($formValues); // check if indexed subforms are returned by looking for array-key 0. // Database ids and timestamps won't be 0 so if that key exists we can // sure it is because Zend_Form has altered the original numeric key. if (in_array('0', $keys)) { $values = array_values($formValues); foreach ($keys as $keyIdx => $keyVal) { if (is_numeric($keyVal) && isset($this->defaultsKeys[$keyVal])) { $keys[$keyIdx] = $this->defaultsKeys[$keyVal]; } } $formValues = array_combine($keys, $values); } return $formValues; }
/** * Process image sharing settings form * @param Zend_Form $form * @param Unsee_Hash $hashDoc * @return boolean */ private function handleSettingsFormSubmit($form, $hashDoc) { // Don't try to process the form if the hash was deleted or the viewer is not the author if (!$hashDoc || !Unsee_Session::isOwner($hashDoc)) { return false; } if ($form->isValid($_POST)) { $values = $form->getValues(); // Changed value of TTL if (isset($values['ttl']) && $hashDoc->ttl === Unsee_Hash::$ttlTypes[0]) { // Revert no_download to the value from DB, since there's no way // it could have changed. It's disabled when ttl == 'first'. unset($values['no_download']); } $expireAt = false; // Apply values from form to hash in Redis foreach ($values as $field => $value) { if ($field == 'strip_exif') { // But skip strip_exif, since it's always on continue; } if ($field === 'ttl') { // Delete after view? if ($value == Unsee_Hash::$ttlTypes[0]) { $hashDoc->max_views = 1; $expireAt = $hashDoc->timestamp + Unsee_Redis::EXP_DAY; // Set to expire within a day after upload } else { $amount = array_search($value, Unsee_Hash::$ttlTypes); $hashDoc->max_views = 0; $expireAt = $hashDoc->timestamp + $amount; } } $hashDoc->{$field} = $value; } if ($expireAt) { $hashDoc->expireAt($expireAt); } } }
/** * @description do auth (: * @throws Evil_Exception|Exception * @param $controller * @param array $login * @param array $password * @param string $tableName * @return int * @author BreathLess, Se# * @version 0.0.2 * @changeLog * 0.0.2 login and password variabled, tableName is dynamic */ public function doAuth($controller, $login = array(), $password = array(), $formConfig = array(), $tableName = 'user') { // Support custom views for auth form $config = Zend_Registry::get('config'); $config = is_object($config) ? $config->toArray() : $config; if (isset($config['evil']['auth']['native']['view']) && !empty($config['evil']['auth']['native']['view'])) { return $this->_doCustomAuth($controller, $config['evil']['auth']['native']['view']); } else { if (empty($formConfig)) { $form = new Evil_Auth_Form_Native(); } else { $form = new Zend_Form($formConfig); } $controller->view->form = $form; if ($controller->getRequest()->isPost()) { if ($form->isValid($_POST)) { $data = $form->getValues(); $login = empty($login) ? array('field' => 'nickname', 'value' => 'username') : $login; $password = empty($password) ? array('field' => 'password', 'value' => 'password') : $password; if (!isset($data[$login['value']]) || !isset($data[$password['value']])) { throw new Exception(' Missed "' . $login['value'] . '" or "' . $password['value'] . '" field'); } $user = Evil_Structure::getObject($tableName); $user->where($login['field'], '=', $data[$login['value']]); if ($user->load()) { if ($user->getValue($password['field']) == md5($data[$password['value']])) { return $user->getId(); } else { throw new Evil_Exception('Password Incorrect', 4042); } } else { throw new Evil_Exception('Unknown user', 4044); } } } } return -1; }
public function indexAction() { $configForm = $this->getInvokeArg('bootstrap')->getResource('configForm'); $deliciousApiForm = new \Zend_Form($configForm->deliciousApi); if ($this->getRequest()->isPost()) { if ($deliciousApiForm->isValid($_POST)) { try { $this->deliciousRepository->saveEntity($deliciousApiForm->getValues()); $this->_helper->systemMessages('notice', 'Einstellungen erfolgreich gespeichert'); } catch (\Exception $e) { $log = $this->getInvokeArg('bootstrap')->log; $log->log($e->getMessage(), \Zend_Log::ERR, array('trace' => $e->getTraceAsString())); $this->_helper->systemMessages('error', 'Einstellungen konnte nicht gespeichert werden'); } } } else { $entity = $this->deliciousRepository->fetchEntity(); if ($entity) { $deliciousApiForm->populate($entity->toArray()); } } $deliciousApiForm->setAction('/admin/delicious'); $this->view->form = $deliciousApiForm; }
/** * Based on the product that has been modified * Pull the correct for, test for validity and save * or return the appropriate errors */ public function processAction() { if (!$this->_request->isXmlHttpRequest() || !$this->_request->isPost() || !$this->_request->getParam('product_category_name')) { $this->_redirect('/admin/products/'); } $return = array(); //Identify the correct Product Form $productGateway = new Products_Model_ProductGateway(); switch ($this->_request->getParam('product_category_name')) { case "Annuity": $form = $productGateway->getForm('ModifyAnnuityProduct'); $validForm = $form->isValid($this->_request->getParams()); break; case "Disability": $form = $productGateway->getForm('ModifyDisabilityProduct'); $validForm = $form->isValid($this->_request->getParams()); break; case "Health": $form = $productGateway->getForm('ModifyHealthProduct'); $validForm = $form->isValid($this->_request->getParams()); break; case "Life": $form = $productGateway->getForm('ModifyLifeProduct'); $validForm = $form->isValid($this->_request->getParams()); break; default: $form = new Zend_Form(); $form->addErrorMessage('Unable to indentify a Valid Form'); $validForm = false; } // Check the form for validity if (!$validForm) { $return['formErrors'] = $form->getMessages(); $return['formResult'] = FALSE; } else { $form->removeElement('product_company_name'); $form->removeElement('product_category_name'); $product = $productGateway->create($form->getValues()); $product->save(); $productId = $this->_request->getParam('product_id'); $flashMessenger = $this->_helper->getHelper('FlashMessenger'); $flashMessenger->setNamespace('notifications')->addMessage($this->_request->getParam('product_name') . ' Product Updated'); if ($this->_request->getParam('close') == 1) { $return['redirect']['location'] = '/admin/products/'; } else { $return['redirect']['location'] = '/admin/products/modify/' . $productId; } } $this->_helper->json->sendJson($return); }
public function testGetValuesReturnsNestedSubFormValuesFromArraysToWhichElementsBelong() { $form = new Zend_Form(); $form->setElementsBelongTo('foobar'); $form->addElement('text', 'firstName') ->getElement('firstName') ->setRequired(true); $form->addElement('text', 'lastName') ->getElement('lastName') ->setRequired(true); $subForm = new Zend_Form_SubForm(); $subForm->setElementsBelongTo('foobar[baz]'); $subForm->addElement('text', 'email') ->getElement('email')->setRequired(true); $subSubForm = new Zend_Form_SubForm(); $subSubForm->setElementsBelongTo('foobar[baz][bat]'); $subSubForm->addElement('checkbox', 'home') ->getElement('home')->setRequired(true); $subForm->addSubForm($subSubForm, 'subSub'); $form->addSubForm($subForm, 'sub') ->addElement('submit', 'save', array('value' => 'submit', 'ignore' => true)); $data = array('foobar' => array( 'firstName' => 'Mabel', 'lastName' => 'Cow', 'baz' => array( 'email' => '*****@*****.**', 'bat' => array( 'home' => 1, ) ) )); $this->assertTrue($form->isValid($data)); $values = $form->getValues(); $this->assertEquals($data, $values); }
/** * @group ZF-3227 */ public function testFormsShouldAllowResetting() { $form = new Zend_Form(); $foo = new Zend_Form_SubForm(array('name' => 'foo', 'elements' => array('one' => 'text', 'two' => 'text'))); $form->addElement('text', 'bar')->addElement('text', 'baz')->addElement('text', 'bat')->addDisplayGroup(array('bar', 'bat'), 'barbat')->addSubForm($foo, 'foo'); $values = array('bar' => 'Bar Value', 'baz' => 'Baz Value', 'bat' => 'Bat Value', 'foo' => array('one' => 'One Value', 'two' => 'Two Value')); $form->populate($values); $test = $form->getValues(); $this->assertEquals($values, $test); $form->reset(); $test = $form->getValues(); $this->assertNotEquals($values, $test); $this->assertEquals(0, array_sum($test)); }
/** * Retrieve all form element values * * @param bool $suppressArrayNotation * @return array */ public function getValues($suppressArrayNotation = false) { $values = parent::getValues($suppressArrayNotation); foreach ($values as $key => $value) { if ($this->getElement($key) instanceof Zend_Form_Element_Submit) { unset($values[$key]); } } return $values; }
public function sending(Zend_Form $form) { $request = Zend_Controller_Front::getInstance()->getRequest(); if ($request->isPost()) { if ($form->isValid($request->getPost())) { //campos e valores $value = $form->getValues(); //chaves de campos $key = array_keys($form->getValues()); //chaves de campos file $key_file = array_keys($_FILES); //concatena chaves e valores do form if (!$this->message) { $msg = "<table style='width:500px'>"; for ($i = 0; $i < count($key); $i++) { $msg .= "<tr>"; $msg .= "<th style='padding:5px; background:#f1f1f1; font-weight:bold; border:1px solid #ccc; text-align:right'>"; $msg .= ucwords($key[$i]); $msg .= "</th>"; $msg .= "<td style='padding:5px; border:1px solid #ccc'>"; $msg .= nl2br($value[$key[$i]]); $msg .= "</td>"; $msg .= "</tr>"; } $msg .= "</table>"; $this->message = $msg; } //envia email $mail = new Zend_Mail('utf-8'); $mail->setFrom($this->from, $this->name); $mail->addTo($this->to); $mail->addBcc($this->bcc); $mail->addCc($this->cc); $mail->setBodyHtml($this->message); $mail->setSubject($this->assunto); for ($x = 0; $x < count($_FILES); $x++) { //recebe nome de campos file $file = $_FILES[$key_file[$x]]; //verifica se recebeu anexo if ($file['error'] == 0) { $filetmp = $file['tmp_name']; $filename = $file['name']; $filetype = $file['type']; $filesize = $file['size']; //anexo(s) $mail->createAttachment(file_get_contents($filetmp), $filetype, Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_BASE64, $filename); } } if (!empty($this->smtp) and !empty($this->username) and !empty($this->password)) { //configuração smtp $config = array('auth' => $this->auth, 'username' => $this->username, 'password' => $this->password, 'ssl' => $this->ssl, 'port' => $this->port); //função smtp $mailTransport = new Zend_Mail_Transport_Smtp($this->smtp, $config); $mail->send($mailTransport); } else { //envio normal $mail->send(); } //retorna para página informada header("location: " . $this->return); } } }
private function handleForm(Zend_Form $form, Staff $staff) { if ($this->_request->isPost() && $form->isValid($this->_request->getPost())) { try { $this->repository->save($staff, $form->getValues()); $this->_helper->entity->getManager()->flush(); // TODO bad design, redirect should not be here. } catch (\PDOException $e) { $this->_helper->flashMessenger(array('error', getGS("Could not save user '\$1'. Please make sure it doesn't already exist", $this->_request->getPost('username')))); $this->_helper->redirector->gotoSimple('add', 'staff', 'admin'); } catch (\InvalidArgumentException $e) { if ($e->getMessage() == 'email') { $this->_helper->flashMessenger(array('error', getGS("Could not save user with e-mail address '\$1'. Please make sure it doesn't already exist", $this->_request->getPost('email')))); } $this->_helper->redirector->gotoSimple('add', 'staff', 'admin'); } catch (\Exception $e) { $this->_helper->flashMessenger(array('error', getGS("Changing user type would prevent you to manage users. Aborted."))); $this->_helper->redirector->gotoSimple('edit', 'staff', 'admin', array('user' => $staff->getId())); } // add default widgets for new staff if ($this->_getParam('action') == 'add') { WidgetManager::SetDefaultWidgets($staff->getId()); } $this->_helper->flashMessenger(getGS('Staff member saved.')); $this->_helper->redirector->gotoSimple('edit', 'staff', 'admin', array('user' => $staff->getId())); } }
$file->setDecorators(array('File', 'Errors')); // Create an instance of Zend_View and set the directory // for the template files $view = new Zend_View(); $view->setScriptPath(__DIR__); // Tell all the elements in the form which view to use when rendering foreach ($form as $item) { $item->setView($view); } // process or display the form if (isset($_POST['submit']) && $form->isValid($_POST)) { $uploadHandler = new Zend_File_Transfer_Adapter_Http(); $uploadHandler->setDestination(__DIR__ . '/uploads/'); try { $uploadHandler->receive(); $data = $form->getValues(); Zend_Debug::dump($data, 'Form Data:'); $fullPath = $uploadHandler->getFileName('file'); $size = $uploadHandler->getFileSize('file'); $mimeType = $uploadHandler->getMimeType('file'); $fileInfo = pathinfo($fullPath); $name = $fileInfo['basename'] . '<br>'; // rename the file for security purpose $newName = 'RM_' . time() . '_' . $fileInfo['basename']; $fullFilePath = __DIR__ . '/uploads/' . $newName; $filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true)); $filterFileRename->filter($fullPath); echo 'thanks <br />'; } catch (Zend_File_Transfer_Exception $e) { echo $e->getMessage(); }
/** * Method for saving a commenter * * @param ZendForm $p_form * @param ICommenter $p_commenter */ private function handleForm(Zend_Form $p_form, $p_commenter) { if ($this->getRequest()->isPost() && $p_form->isValid($_POST)) { $values = $p_form->getValues(); $values['ip'] = $this->getRequest()->getClientIp(); $values['time_created'] = new DateTime(); $this->commenterRepository->save($p_commenter, $values); $this->commenterRepository->flush(); $this->_helper->flashMessenger(getGS('Commenter "$1" saved.', $p_commenter->getName())); $this->_helper->redirector->gotoSimple('index'); } }
/** * After validation we clean the form data to remove all * entries that do not have elements in the form (and * this filters the data as well). */ public function cleanFormData() { $this->formData = $this->_form->getValues(); }