Mostrar mensagens com a etiqueta symfony. Mostrar todas as mensagens
Mostrar mensagens com a etiqueta symfony. Mostrar todas as mensagens

segunda-feira, 25 de agosto de 2014

dyld: Symbol not found: __cg_jpeg_resync_to_restart

Ao usar o MAMP PRO e o YUI Compressor surgiu-me este erro:

==> /Applications/MAMP/logs/apache_error.log <==
dyld: Symbol not found: __cg_jpeg_resync_to_restart
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
  Expected in: /Applications/MAMP/Library/lib/libJPEG.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO

==> /Applications/MAMP/logs/php_error.log <==
[25-Aug-2014 12:06:04 Europe/Lisbon] YUI Compressor returned error
O problema é que o MAMP PRO faz export da variável DYLD_LIBRARY_PATH. Solução: editar o ficheiro: "/Applications/MAMP/Library/bin/envvars" e comentar o seu conteúdo. Ficheiro original:
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# envvars-std - default environment variables for apachectl
#
# This file is generated from envvars-std.in
#
if test "x$DYLD_LIBRARY_PATH" != "x" ; then
  DYLD_LIBRARY_PATH="/Applications/MAMP/Library/lib:$DYLD_LIBRARY_PATH"
else
  DYLD_LIBRARY_PATH="/Applications/MAMP/Library/lib"
fi
export DYLD_LIBRARY_PATH
#
Ficheiro editado:
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# envvars-std - default environment variables for apachectl
#
# This file is generated from envvars-std.in
#
#if test "x$DYLD_LIBRARY_PATH" != "x" ; then
#  DYLD_LIBRARY_PATH="/Applications/MAMP/Library/lib:$DYLD_LIBRARY_PATH"
#else
#  DYLD_LIBRARY_PATH="/Applications/MAMP/Library/lib"
#fi
#export DYLD_LIBRARY_PATH
#

domingo, 16 de março de 2014

EmbedForm with new relation

To insert new attributes to a Product in the default form we just need those few steps:

In the productForm class create the relation with the attribute form.

public function configure() {
    /* Create embedForm with an empty attribute */
    $new_attribute = new ProductAttribute();
    $new_attribute->setProduct($this->object);
    $this->embedForm('new_attribute', new ProductAttributeForm($new_attribute));
    $this->embedRelation('Attributes', new ProductAttributeForm());
}

...and we rewrite the saveEmbeddedForms methods
public function saveEmbeddedForms($con = null, $forms = null) {
    try {
        $new_attribute_form = $this->getEmbeddedForm('new_attribute');
        $values             = $this->getValue('new_attribute');

        /* Validations Rules to save the relation */
        if (empty($values['attribute_id'])) {
            unset($this['new_attribute']);
        }
    } catch (InvalidArgumentException $e) {
        error_log($e->getTraceAsString());
    }
    return parent::saveEmbeddedForms($con, $forms);
}

sexta-feira, 8 de fevereiro de 2013

Symfony, Disable CSRF protection

Desactivar a protecção CSRF no formulário:

public function configure()
{
$this->disableCSRFProtection();
}


Desactivar a protecção CSRF no settings.yml:

.settings:
csrf_secret: false

quinta-feira, 8 de novembro de 2012

Symfony correr task em acção

Geralmente criamos uma task symfony para correr numa cron, mas por vezes pode-nos dar muito jeito correr a task ao clicar num botão ou depois de guardar um objecto, para resolver isso ficam aqui as poucas linhas que necessitam para correr a task:

// In sfActions
chdir(sfConfig::get('sf_root_dir')); // Trick plugin into thinking you are in a project directory
$task = new sfMyVerySpecialTask($this->dispatcher, new sfFormatter());
$task->run(array('argument_name' => 'argument'), array('option_name' => 'option'));

Fonte: link

segunda-feira, 5 de novembro de 2012

Symfony Task error de "default context"

Um erro recorrente em Symfony é o tão conhecido The "default" context does not exist., este erro dá-se quando tentamos aceder às variáveis de context numa Task.

Para resolver é simples, basta colocar a linha seguinte no execute da task.
sfContext::createInstance($this->configuration);

quinta-feira, 13 de setembro de 2012

Symfony User Filters

Muitas vezes é importante conseguirmos saber os filtros que o utilizador criou para apresentarmos os dados pedidos.

Estes filtros são guardados como atributo do sf_user, para os conseguir obter basta utilizar estas linhas:

$admin_module = $sf_user->getAttributeHolder()->getAll('admin_module');
        $filters = $admin_module['page.filters'];

em que o page é o nome do modulo que estão a editar.


segunda-feira, 10 de setembro de 2012

Download de ficheiro em Symfony

Por vezes esta simples acção pode ser um bocado complicada. Vamos então ver como podemos fazer o download de um ficheiro de forma simples em Symfony.

Criar-mos a acção executeDownload() e, após criar o ficheiro basta colocar estas poucas linhas:

$resp = $this->getResponse();

    $resp->setContentType('text/csv');
    $resp->setHttpHeader(
              'Content-Disposition', 
              'attachment; filename="' . basename($file_path) . '"');
    $resp->setContent(file_get_contents($file_path));

    return sfView::NONE;

segunda-feira, 3 de setembro de 2012

Widgets Template - Row Format

Personalizar os formulários do Symfony pode ser um castigo, a menos que consigamos perceber como funcionam e as coisas tornam-se mais simples.

Até ao dia de hoje, sempre que queria modificar um formulário editava o template e reescrevia o html.

posso fazer o mesmo com apenas estava linha de código no formulário:
$this->widgetSchema
     ->getFormFormatter()
     ->setRowFormat('%label%%field%%help%%hidden_fields%');

Podemos utilizar os seguintes atributos:

%label%
      %field%
      %error%
      %help%
      %hidden_fields%

quarta-feira, 8 de agosto de 2012

Criar um validador personalizado em symfony

Por vezes os Validators disponíveis no Symfony não são sufientes para validar os nossos campos, principalmente quando um campo depende de outro, p.e.:
se cmb_a is cheched e cmb_b is checked

       então

     //acção

       senão

     //erro!

Para tal, necessitamos de criar Validators personalizados e aplica-los ao nosso campo. Para tal na nossa classe de formulário acrescentamos as seguintes linhas:

public function configure()
{
    parent::configure();

    $this->validatorSchema['my_field'] = new sfValidatorCallback(
                    array('callback' =>
                        array($this, 'validateMyField')
                    )
    );

}

public function validateMyField($validator, $value)
{
    /* All my action goes here */
    $tainted_values = $this->getTaintedValues();

    if ($tainted_values['my_field_2'] > 0 && $value != '')
    {
        return $value;
    }
    else
    {
        throw new sfValidatorError($validator, "I guess something goes wrong here!");
    }
}


No método validateMyField podemos aceder aos valores todos do formulário obtendo os Tainted values disponíveis utilizando o método getTaintedValues da classe dos formulários.

Realizadas as verificações pretendidas devolvemos o valor ($value) do campo validado ou despoletamos um erro que será apresentado pelo método renderError do formulário.










quarta-feira, 8 de junho de 2011

Criar Mensagens no Log

Para fazer debug às nossas aplicações, pode dar jeito fazer um logo do que fazemos, para tal podemos utilizar o método error_log(), mas se estivermos com a utilizar Symfony, podemos utilizar o log do Symfony. Como fazer isso? Simples...

Podemos inserir vários tipos de mensagem:
emerg, alert, crit, err, warning, notice, info, debug

Na action:
$this->logMessage('Mensagem de Info na action!', 'info');

Fora da action:
sfContext::getInstance()->getLogger()->alert('Mensagem de Alert fora da action!');