Latest 100 public
snipts » symfony
showing 1-20 of 57 snipts for symfony
-
∞ Starts to translate FormChoices in filters for boolean columns
/** * Project filter form base class. * * @package filters * */ abstract class BaseFormFilterDoctrine extends sfFormFilterDoctrine { /** * Used in generated forms when models use inheritance. */ protected function setupInheritance() { // Nastaveni prekladoveho slovniku pro form formater $this->widgetSchema->getFormFormatter()->setTranslationCatalogue('messages'); } }
-
∞ symfonty textarea attributes
<?php $this->getWidget('data')->setAttribute('cols', 50); $this->getWidget('data')->setAttribute('rows', 20); ?>
-
∞ Symfony cookies
#in factories.yml under the section all add storage: class: sfSessionStorage param: session_name: cookieName
-
∞ Browser culture detection
<?php /** * Setup user culture from request * * from http://www.symfony-project.com/snippets/snippet/80 * Thanks to François Zaninotto * Thanks to Garfield-fr on #symfony-fr * * Add the following lines in your app.yml to configure your application available languages. * all: * accepted: * languages: [en, fr] * * Then add this to your filters.yml * * # Filter that setup user culture * mySwitchLanguageFilter: * class: SwitchLanguageFilter * * @package SwitchLanguageFilter * @subpackage filter * @author Pierre-Yves Landuré <py.landure@dorigo.fr> */ class SwitchLanguageFilter extends sfFilter { /** * Check that the language is a valid application culture. * @param string $language The tested language code * @param string $default_language The default language code * * @return string $language if no accepted languages is set, * else $language if it is in accepted languages * else $default_language */ private function getAvailableCulture($language, $default_language = null) { $all_languages = sfConfig::get('app_accepted_languages', array()); if(count($all_languages)) { if(in_array($language, $all_languages)) // Test if language is available { return $language; } else // Else test if first part of language is available { $language_parts = explode('_', $language); if(count($language_parts)) { if(in_array($language_parts[0], $all_languages)) { return $language_parts[0]; } } } return $default_language; } return $language; } /** * The filter call. */ public function execute ($filterChain) { $context = $this->getContext(); $user = $context->getUser(); $default_culture = sfConfig::get('sf_i18n_default_culture'); $selected_culture = $user->getCulture(); if(!$user->getAttribute('sf_culture_autodetected', false)) { $browser_languages = $context->getRequest()->getLanguages(); foreach($browser_languages as $language) { $allowed_culture = $this->getAvailableCulture($language); if($allowed_culture) { $selected_culture = $allowed_culture; break; } } $user->setAttribute('sf_culture_autodetected', true); } $selected_culture = $context->getRequest()->getParameter('sf_culture', $selected_culture); $selected_culture = $this->getAvailableCulture($selected_culture, $default_culture); if($selected_culture != $user->getCulture()) { // The user wants to see the page in another language $user->setCulture($selected_culture); } $filterChain->execute(); } }
-
∞ symfony global errors
<?php $num_errores_totales = count($form->getErrorSchema()->getErrors()); $num_errores_globales = count($form->getErrorSchema()->getGlobalErrors()); if (0 == $num_errores_totales - $num_errores_globales){ echo $form->renderGlobalErrors(); } ?>
-
∞ symfony ssl redirect filter
http://grahamc.com/blog/forcing-ssl-with-symfony-1-2 -
∞ Symfony, customize query of admin generator list view
/** * Customize query used to generate * the list(index) view of an admin generator module * * To customize the query simply override the buildQuery * method of the Actions class or buildQuery of the *FormFilterClass. * In most cases is usefull to override the *FormFilterClass where are * also defined the custom add%ColumnName%ColumnQuery * * @author Francesco Tassi http://flavors.me/ftassi <tassi.francesco@gmail.com> */ protected function buildQuery() { $query = parent::buildQuery(); //Query customization $query->addWhere('item_id = ?', 1); return $query; }
-
∞ How to implement a choice in a form?
http://www.symfony-project.org/cookbook/1_2/en/make-a-choice The following table summarizes the different configuration of sfWidgetFormChoice and the renderer widget used by symfony: sfWidgetFormChoice expanded is false expanded is true multiple is false sfWidgetFormSelect sfWidgetFormSelectRadio multiple is true sfWidgetFormSelectMany sfWidgetFormSelectCheckbox
-
∞ slugify
<?php static public function slugify($text) { $text = preg_replace('~[^\\pL\d]+~u', '-', $text); $text = trim($text, '-'); $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); $text = strtolower($text); $text = preg_replace('~[^-\w]+~', '', $text); if (empty($text)){ return 'n-a'; } return $text; } ?>
-
∞ File uploads in Symfony 1.2, my take
<?php // FILE lib/model/Model.php: class Model { /** * Returns the abs path to a subdir of uploads specific for this model. * * If given a $path, it will be concatenated at the end. * * @param string $path optional relative path of a file inside the dir * @return string complete path to subdir or file */ public function getUploadPath($path = NULL) { return sfConfig::get('sf_upload_dir').'/event/' . $path; } /** * Returns abs path relative to the docroot. * * @param string $path * @return string */ public function getWebPath($path = NULL) { return str_replace(sfConfig::get('sf_web_dir'), '', $this->getUploadPath($path)); } } // FILE lib/form/ModelForm.php: class ModelForm extends sfPropelForm { public function configure() {} /** * Loops through all form values, updates all files values to be absolute paths relative to the docroot. * Calls $model->getWebPath(), but the code is otherwise generally re-usable. * * (non-PHPdoc) * @see symfony/plugins/sfPropelPlugin/lib/form/sfFormPropel#updateObject($values) */ public function updateObject($values = null) { $object = parent::updateObject($values); foreach ($this->values as $field => $value) { if ($value instanceof sfValidatedFile) { $column = call_user_func(array(constant(get_class($object).'::PEER'), 'translateFieldName'), $field, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME); $getter = 'get'.$column; $setter = 'set'.$column; $object->$setter($object->getWebPath($object->$getter())); } } return $object; } } ?>
-
∞ object routing
//routing.yml job_show_user: url: /job/:company_slug/:location_slug/:id/:position_slug class: sfPropelRoute options: { model: JobeetJob, type: object } param: { module: job, action: show } requirements: id: \d+ sf_method: [get] <?php class jobActions extends sfActions { public function executeShow(sfWebRequest $request) { $this->job = $this->getRoute()->getObject(); $this->forward404Unless($this->job); } // ... } ?>
-
∞ add html suffic to all routes
//config/factories.yml all: routing: class: sfPatternRouting param: generate_shortest_url: true extra_parameters_as_query_string: true suffix: .html
-
∞ Symfony User Credentials
http://librosweb.es/jobeet/capitulo13/la_seguridad_de_la_aplicacion.html -
∞ redirect from component
<? $this->getController()->redirect ('@homepage'); ?>
-
∞ Load helper from action in symfony 1.2, 1.3,1.4
$this->getContext()->getConfiguration()->loadHelpers('Partial'); -
∞ web debug database
//databases.yml change classname: PropelPDO por class:name: DebugPDO
-
∞ sfResizethumbnail
<?php /** * sfResizedFile represents a resized uploaded file. * * @package symfony * @subpackage validator * @author Malas * @version 0.1 */ class sfResizedFile extends sfValidatedFile { /** * Saves the uploaded file. * * This method can throw exceptions if there is a problem when saving the file. * * If you don't pass a file name, it will be generated by the generateFilename method. * This will only work if you have passed a path when initializing this instance. * * @param string $file The file path to save the file * @param int $fileMode The octal mode to use for the new file * @param bool $create Indicates that we should make the directory before moving the file * @param int $dirMode The octal mode to use when creating the directory * * @return string The filename without the $this->path prefix * * @throws Exception */ public function save($file = null, $fileMode = 0666, $create = true, $dirMode = 0777) { if (is_null($file)) { $file = $this->generateFilename(); } if ($file[0] != '/' && $file[0] != '\\' && !(strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/'))) { if (is_null($this->path)) { throw new RuntimeException('You must give a "path" when you give a relative file name.'); } $smallFile = $this->path.DIRECTORY_SEPARATOR.'s_'.$file; $file = $this->path.DIRECTORY_SEPARATOR.$file; } // get our directory path from the destination filename $directory = dirname($file); if (!is_readable($directory)) { if ($create && !mkdir($directory, $dirMode, true)) { // failed to create the directory throw new Exception(sprintf('Failed to create file upload directory "%s".', $directory)); } // chmod the directory since it doesn't seem to work on recursive paths chmod($directory, $dirMode); } if (!is_dir($directory)) { // the directory path exists but it's not a directory throw new Exception(sprintf('File upload path "%s" exists, but is not a directory.', $directory)); } if (!is_writable($directory)) { // the directory isn't writable throw new Exception(sprintf('File upload path "%s" is not writable.', $directory)); } // copy the temp file to the destination file $thumbnail = new sfThumbnail(68, 183, true, true, 85); $thumbnail->loadFile($this->getTempName()); $thumbnail->save($smallFile, 'image/jpeg'); $thumbnail = new sfThumbnail(188, 684, true, true, 85, 'sfGDAdapter'); $thumbnail->loadFile($this->getTempName()); $thumbnail->save($file, 'image/jpeg'); // chmod our file chmod($smallFile, $fileMode); chmod($file, $fileMode); $this->savedName = $file; return is_null($this->path) ? $file : str_replace($this->path.DIRECTORY_SEPARATOR, '', $file); } } //objectForm.class.php $this->widgetSchema['imagen'] = new sfWidgetFormInputFileEditable(array( 'label' => 'Foto del producto', 'file_src' => '/uploads/products/s_'.$this->getObject()->getImagen(), 'is_image' => true, 'edit_mode' => !$this->isNew(), 'template' => '<div>%file%<br />%input%<br />%delete% borrar foto</div>' )); //validate widgets. $this->validatorSchema['imagen'] = new sfValidatorFile(array( 'required' => false, 'mime_types' => 'web_images', 'path' => sfConfig::get('sf_upload_dir').'/products', 'validated_file_class' => 'sfResizedFile', )); $this->validatorSchema['imagen_delete'] = new sfValidatorPass();
-
∞ custom filter
<?php class VinoFormFilter extends BaseVinoFormFilter { public function configure() { $this->setWidget('nombre', new sfWidgetFormFilterInput()); $this->setValidator('nombre', new sfValidatorPass()); $this->validatorSchema->addOption('allow_extra_fields', true); } public function getFields() { return array_merge(array('nombre' => 'Nombre'), parent::getFields()); } protected function addNombreColumnCriteria(Criteria $criteria, $field, $values){ $criteria->add(ItemPeer::NOMBRE, "%".$values['text']."%", Criteria::LIKE); } } ?>
-
∞ Start coding project
$ mysqladmin -uroot -p create ashq $ php symfony configure:database "mysql:host=localhost;dbname=ashq" sqadri myPasswd $ php symfony propel:build-all $ php symfony propel:generate-module survey map MAP
-
∞ Freeze project
# To freeze a symfony 1.2 project $ rm web/sf $ symfony project:freeze /usr/share/php/symfony


