Mostrando postagens com marcador PHP. Mostrar todas as postagens
Mostrando postagens com marcador PHP. Mostrar todas as postagens

domingo, 14 de fevereiro de 2016

General error: 1364 Field 'id' doesn't have a default value

Hi!

The id you defined for your entity is not identity. It must be!

Good luck!

Error: SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value
If you are using SQL keywords as table column names, you can enable identifier quoting for your database connection in config/app.php.
SQL Query:
INSERT INTO projetos (user_id, nome) VALUES (:c0, :c1)

segunda-feira, 8 de fevereiro de 2016

Login, Logout is making you insane? / CakePHP 3.0 / That's how I did.

Hi!

This thing of login, logout is p. in the a.. Well that's how I did mine

        $this->loadComponent('Auth', [
                'authorize' => 'Controller',
                'authenticate' => [
                'Form' => [
                'fields' => [
                'username',
                'password' => 'password'
                ]
                ]
                ],
                'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
                ],
                'loginRedirect' => [
                                'controller' => 'Users',
                                'action' => 'index'
                            ],
                'logoutRedirect' => [
                                'controller' => 'Users',
                                'action' => 'login'
                            ]                        
                ]);
                // Allow the display action so our pages controller
                // continues to work.
                $this->Auth->allow(['display']);
    }

Hope it helps.

Good Luck!


sábado, 30 de janeiro de 2016

DROPDOWNLIST - You want to show the name, not the id. Me too. That's how I did it.

Hi!

Straight to the point.

        First, I was studying the tutorial. And was working with treelist. This is no good for me. So, I asked myself,  how do make this dropdownlist show the name? The standard answer is, "YOU SHOULD USE VIRTUAL FIELD". And I found it really annoying. So, I found out this solution.

        //You write this in your controller

        $query = $this->Articles->Categories->find('all', array('fields' => array('id', 'name')));
        foreach($query as $row)
        {
            $id = $row['id'];
            $name = $row['name'];
            $categories[$id] = $name;
        }

       //You write this in  your template
     
       echo $this->Form->input('category_id', array('type' => 'select','options'=> $categories));

And you are done! And of story!

Good luck!

PS: I'm new to cakePHP. This was really annoying to find out.

More informations click on the link bellow

http://stackoverflow.com/questions/19920094/cakephp-format-findall-to-list-in-view

Lines of the tutorial are incomplete - Page 90 - CakePHP Cookbook

Hi!

I found this problem when I was studying the tutorial

CakePHP Cookbook Documentation
Release 3.x
Cake Software Foundation
January 18, 2016

<td><?= $category->id ?></td>
<td><?= $category->parent_id ?></td>
<td><?= $category->lft ?></td>
<td><?= $category->rght ?></td>
<td><?= h($category->name) ?></td>
<td><?= h($category->description) ?></td>
<td><?= h($category->created) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $category->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $category->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $category->id], 
<?= $this->Form->postLink(__('Move down'), ['action' => 'moveDown', $category->
<?= $this->Form->postLink(__('Move up'), ['action' => 'moveUp', $category-></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>

Correction

    <?= $this->Html->link(__('View'), ['action' => 'view', $category->id]) ?>
    <?= $this->Html->link(__('Edit'), ['action' => 'edit', $category->id]) ?>
    <?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $category->id]) ?>
    <?= $this->Form->postLink(__('Move down'), ['action' => 'moveDown', $category->id]) ?>
    <?= $this->Form->postLink(__('Move up'), ['action' => 'moveUp', $category->id]) ?>

Good luck!

sábado, 23 de janeiro de 2016

Error: Class 'App\Model\Entity\DefaultPasswordHasher' not found


Hi!

use Cake\Auth\DefaultPasswordHasher; <--------------- Maybe you forgot to add this.

protected function _setPassword($value)
{
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}

Good Luck!

quinta-feira, 21 de janeiro de 2016

- cakephp/cakephp 3.1.7 requires ext-intl * -> the requested PHP extension intl is missing from your system.


Hi!

If you were trying to execute this

C:\Users\daniel>composer create-project --prefer-dist cakephp/app bookmarker

And received this message

 - cakephp/cakephp 3.1.7 requires ext-intl * -> the requested PHP extension intl is missing from your system.

Solution I found

uncomment this entry of your PHP.ini

;extension=php_intl.dll

After this, you're gonna a result similar to this bellow.


C:\Users\daniel>composer create-project --prefer-dist cakephp/app bookmarker
You are running composer with xdebug enabled. This has a major impact on runtime
 performance. See https://getcomposer.org/xdebug
Installing cakephp/app (3.1.2)
  - Installing cakephp/app (3.1.2)
    Loading from cache

Created project in bookmarker
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing aura/installer-default (1.0.0)
    Downloading: 100%

  - Installing cakephp/plugin-installer (0.0.12)
    Downloading: 100%

  - Installing psr/log (1.0.0)
    Downloading: 100%

  - Installing nesbot/carbon (1.13.0)
    Downloading: 100%

  - Installing mobiledetect/mobiledetectlib (2.8.19)
    Downloading: 100%

  - Installing aura/intl (1.1.1)
    Downloading: 100%

  - Installing ircmaxell/password-compat (v1.0.4)
    Downloading: 100%

  - Installing cakephp/cakephp (3.1.7)
    Downloading: 100%

  - Installing symfony/yaml (v3.0.1)
    Downloading: 100%

  - Installing symfony/filesystem (v3.0.1)
    Downloading: 100%

  - Installing symfony/config (v3.0.1)
    Downloading: 100%

  - Installing symfony/polyfill-mbstring (v1.0.1)
    Downloading: 100%

  - Installing symfony/console (v3.0.1)
    Downloading: 100%

  - Installing robmorgan/phinx (v0.5.1)
    Downloading: 100%

  - Installing cakephp/migrations (1.5.2)
    Downloading: 100%

  - Installing jakub-onderka/php-console-color (0.1)
    Downloading: 100%

  - Installing jakub-onderka/php-console-highlighter (v0.3.2)
    Downloading: 100%

  - Installing dnoegel/php-xdg-base-dir (0.1)
    Downloading: 100%

  - Installing nikic/php-parser (v2.0.0)
    Downloading: 100%

  - Installing symfony/var-dumper (v3.0.1)
    Downloading: 100%

  - Installing psy/psysh (v0.6.1)
    Downloading: 100%

  - Installing jdorn/sql-formatter (v1.2.17)
    Downloading: 100%

  - Installing cakephp/debug_kit (3.2.5)
    Downloading: 100%

  - Installing cakephp/bake (1.1.3)
    Downloading: 100%

symfony/console suggests installing symfony/event-dispatcher ()
symfony/console suggests installing symfony/process ()
symfony/var-dumper suggests installing ext-symfony_debug ()
psy/psysh suggests installing ext-pcntl (Enabling the PCNTL extension makes PsyS
H a lot happier :))
psy/psysh suggests installing ext-posix (If you have PCNTL, you'll want the POSI
X extension as well.)
psy/psysh suggests installing ext-readline (Enables support for arrow-key histor
y navigation, and showing and manipulating command history.)
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to
 work.)
cakephp/debug_kit suggests installing ext-sqlite (DebugKit needs to store panel
data in a database. SQLite is simple and easy to use.)
Writing lock file
Generating autoload files
> Cake\Composer\Installer\PluginInstaller::postAutoloadDump
> App\Console\Installer::postInstall
Created `config/app.php` file
Set Folder Permissions ? (Default to Y) [Y,n]? Y
Updated Security.salt value in config/app.php

C:\Users\daniel>


















sábado, 14 de julho de 2012

PHP - Exemplo do uso de classe e array

Veja bem,

Este é um exemplo muito simples de como trabalhar com classes no PHP.

Olho no lance.

<?php
$arrEstadoString = explode("|", "AM|SP|RJ|");
$arrEstadoObetos = array();

//Criação do array de objetos.............................................

for ($i=0;$i<count($ arrEstadoString ) ;$i++)
{
   $EstadoObjeto = new Estado();
   $EstadoObjeto->sigla = $arrEstadoSring[$i];
   $arrEstadoObjetos[$i] = $EstadoObjeto;
}

//Imprimindo o conteúdo do array.....................................
for ($i=0;$i<count($ arrEstadoObjetos ) ;$i++)
{
   echo $arrEstadoObjetos[$i]->sigla;
}

// Fim.


class Estado
{
    public $sigla;
} 

?>

Et voilà!

quarta-feira, 4 de julho de 2012

Editor PHP

Veja bem,

Você está procurando um editor PHP?

Minha sugestão: phpDesigner8.

Preço: U$39 (Personal Use)
http://www.mpsoftware.dk/buy.php

That's all folks.

sábado, 30 de junho de 2012

http://www.indcep.com.br - Projeto pessoal

"Hi, inhabitants of narnia, how are you?"

Veja bem, os posts deste website referem-se aos problemas que encontrei durante a construção deste website http://www.indcep.com.br .

Construí este site para aprender a trabalhar com coordenadas geodésicas o que, aliás, não é trivial.

Tecnologias envolvidas:

PHP
MySQL
Apache
JQuery
JSON
Yii

Toda semana implemento uma coisa nova.

Caso tenha alguma questão ou sugestão, entre em contato pelo formulário contato presente no website.

That's all folks.

sábado, 16 de junho de 2012

Cannot modify header information - headers already sent by (output started at /home/indcepco/public_html/home/index.php:2)

Veja bem, esse erro é uma M!!!!!!!!!


Cannot modify header information - headers already sent by (output started at /home/indcepco/public_html/home/index.php:2)


Como resolvi.


Descobri um arquivo php, que tinha um espaço em branco no início.


Ou seja,


antes da cláusula <?php, tinha um enter.


E o tempo que demorei para descobir isso?

domingo, 3 de junho de 2012

Highcharts - Ao invés do mês atual o gráfico mostra o próximo mês

Veja bem,

Esse é um daqueles erros que vai derreter seu cérebro.
Estava eu tranquilamente usando o highcharts (http://www.highcharts.com), quando notei que o mês não etava aparecendo corretamente.
Ou seja, eu colocava a data no eixo X, 20/06/2012, o ponto marcava 20/07/2012.
Daí pensei, é o relógio do máquina, é uma configuração do PHP, é uma configuração do APACHE?
Depois de 4horas descobri algo que talvez você não saiba:


series: [{
name: 'Winter 2007-2008',
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
data: [
[Date.UTC(1970,  9, 27), 0   ],
[Date.UTC(1970, 10, 10), 0.6 ],
[Date.UTC(1970, 10, 18), 0.7 ],
[Date.UTC(1970, 11,  2), 0.8 ],

É ou não é de deixar qualquer um doido?

Como é que eu vou adivinhar que alguém teve a brilhante ideia de definir 0 para início da sequencia dos meses e não 1?

PS: E nisso vão horas... E tome!


sábado, 2 de junho de 2012

Yii - Bug que vai derreter seu cérebro - Trying to get property of non-object

Veja bem,

Se você define no MySql um campo como decimal (9,7) o gii do yii gera a seguinte regra
array('latitude, longitude', 'length', 'max'=>9).

Quando você executa o método save do model você receberá este erro


2012/06/03 01:59:58 [error] [php] Trying to get property of non-object (C:\xampp\htdocs\indcep\protected\models\TargetVote.php:182)
Stack trace:
#0 C:\xampp\htdocs\indcep\protected\controllers\TargetVoteController.php(163): TargetVote->save()
#1 C:\xampp\htdocs\yii\framework\web\actions\CInlineAction.php(50): TargetVoteController->actionCreate()
#2 C:\xampp\htdocs\yii\framework\web\CController.php(309): CInlineAction->runWithParams()
#3 C:\xampp\htdocs\yii\framework\web\filters\CFilterChain.php(134): TargetVoteController->runAction()
#4 C:\xampp\htdocs\yii\framework\web\filters\CFilter.php(41): CFilterChain->run()
#5 C:\xampp\htdocs\yii\framework\web\CController.php(1146): CAccessControlFilter->filter()
#6 C:\xampp\htdocs\yii\framework\web\filters\CInlineFilter.php(59): TargetVoteController->filterAccessControl()
#7 C:\xampp\htdocs\yii\framework\web\filters\CFilterChain.php(131): CInlineFilter->filter()
#8 C:\xampp\htdocs\yii\framework\web\CController.php(292): CFilterChain->run()
#9 C:\xampp\htdocs\yii\framework\web\CController.php(266): TargetVoteController->runActionWithFilters()
#10 C:\xampp\htdocs\yii\framework\web\CWebApplication.php(276): TargetVoteController->run()
#11 C:\xampp\htdocs\yii\framework\web\CWebApplication.php(135): CWebApplication->runController()
#12 C:\xampp\htdocs\yii\framework\base\CApplication.php(162): CWebApplication->processRequest()
#13 C:\xampp\htdocs\indcep\index.php(15): CWebApplication->run()
REQUEST_URI=/indcep/index.php?r=targetVote/create
in C:\xampp\htdocs\indcep\protected\models\TargetVote.php (182)
in C:\xampp\htdocs\indcep\protected\controllers\TargetVoteController.php (163)
in C:\xampp\htdocs\indcep\index.php (15)

decimal (9,7) significa 9 casas decimais no total com 7 casas decimais possíveis a direita.
Ou seja
'max'=>9 faz sentido.
Porém o yii não leva em conta o ponto decimal e o sinal para dizer se é positivo ou negativo.

Ou seja, o correto é
'max'=>11 

Ain't that a bitch?

terça-feira, 29 de maio de 2012

Utilização do CURL do PHP

Veja bem,

Este é um exemplo de utilização do CURL.


        $ch = curl_init();
        $url = "http://" .  $_SERVER['SERVER_NAME'] . "/cliente/utilitario/lerrg.php?rg=" . $rg;                      
        $timeout = 20;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false); 
        curl_setopt($ch, CURLOPT_NOBODY, false); // remove body 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);              
        curl_close($ch);
        return $data;
Coloquei em vermelho dois parâmetros "traiçoeiros". Apesar de estar escrito Header e Body, eles não se referem ao Header ou Body da página que você está chamando.
Utilize esta configuração para acessar o conteúdo da página sem problemas.

That's it!

domingo, 27 de maio de 2012

Classe de validação : CValidator

Veja bem,

Se você está que nem eu, desenvolvendo com yii já deve ter chegado a questão das classes de validação. Se não chegou, vai chegar.

No meu caso construí uma classe de validação para CEP.

Primeiro passo:

Na classe Model


    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('code',
                    'required'),
            array(
                'code','cep'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'id, code, noise, accessibility, neighborhood, afforestation, violence',
                'safe',
                'on' => 'search'),
            );
    }

//Segundo passo criar a classe de validação..........


class cep extends CValidator
{ //início da Classe

    public function validateAttribute($object, $attribute)
    {
        $message = utf8_encode("não é válido ou não existe.");
        if (!$this->validaCEP($object->$attribute)) {
            $message = $this->message !== null ? $this->message : Yii::t('cep',
                '{attribute} ' . $message);
            $this->addError($object, $attribute, $message);
        }

    }


    public function clientValidateAttribute($object, $attribute)
    {
        return "";

    }

    private function validaCEP($cep)
    {
        $cep = trim($cep);
        if (!is_numeric($cep)) {
            return false;
        }
        if (strlen($cep) != 8) {
            return false;
        }
       
        $content = $this->get_data("utilitario/lercep.php?cep=$cep");
        $content = trim($content);
       
        if (strlen($content) == 0)
        {
            return false;
        }
               
        return true;

    }

    function get_data($url)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

} //fim da Classe


Para mais detalhes acesse este link
http://abelcorreadias.blogspot.com.br/2012/01/criando-um-validator-para-o-campo-cpf.html

PS: utilitario/lercep.php não é um php mágico que acesse o cep de algum site como república virtual ou mesmo o site do correio. Estou acessando minha própria base de CEP. Atenção: a base de CEP do correio é gigantesca.

Fatal error: Call to undefined function curl_init()

Veja bem,

estava eu trabalhando com o yii (framework php) e tomei este erro
Fatal error: Call to undefined function curl_init()
Obs: Estou usando o XAMPP

Como resolve?

Acesse o arquivo php.ini
xxxxxx\php\php.ini
descomente
;extension=php_curl.dll
tira o ponto e vírcula
extension=php_curl.dll
Reinicia a máquina.

Voilà!

Problemas com acentuação (a revanche)


Veja bem,

O conteúdo que vem do banco do MySql estava vindo perfeito. Entretanto os labels, das páginas PHP estava aparecendo com problemas.

Exemplo:

Arboriza��o *

Como resolvi:

$label_arborizacao = utf8_encode("Arborização");
echo $label_arborizacao;

Resultado

Arborização.

Voilà!

domingo, 6 de maio de 2012

yii - Funcionou

Consegui instalar e fazer funcionar o yii.

yii - Problemas na hora de gerar o test drive.


C:\>C:\xampp\htdocs\yii\framework\yiic webapp C:\xampp\htdocs\testdrive
'"php.exe"' is not recognized as an internal or external command,
operable program or batch file.

http://www.yiiframework.com

Solução

Estou utilizando windows como S.O.
Desta forma, basta alterar o framework\yiic.bat

O meu yiic. bat ficou assim


cd c:\xampp\php
@echo off

rem -------------------------------------------------------------
rem  Yii command line script for Windows.
rem
rem  This is the bootstrap script for running yiic on Windows.
rem
rem  @author Qiang Xue <qiang.xue@gmail.com>
rem  @link http://www.yiiframework.com/
rem  @copyright Copyright &copy; 2008 Yii Software LLC
rem  @license http://www.yiiframework.com/license/
rem  @version $Id: yiic.bat 2485 2010-09-19 17:07:11Z qiang.xue $
rem -------------------------------------------------------------

@setlocal

set YII_PATH=%~dp0

if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe

"%PHP_COMMAND%" "%YII_PATH%yiic" %*

@endlocal

----------------------------------------------------------------------------------------------------

Pequena explicação

cd c:\xampp\php -> é caminho onde está o php
Acabei de ler o livro
FAÇA UM SITE
ORIENTADO POR PROJETO
PHP 5.2
MYSQL 5.0
COMÉRCIO ELETRÔNICO
- CARLOS A. J. OLIVERO -
31 CAPÍTULOS
Vários laboratórios.
Depois de finalizar todos os laboratórios você terá um site de comércio eletrônico quase perfeito.
Existem alguns bugs muito simples de serem corrigods.
Tempo para finalizar o livro - 2 semanas.
Número de páginas: 400