「cakephp」カテゴリーアーカイブ

uploadpackの使い方

参考:http://www.kaasan.info/archives/2482

ダウンロード
https://github.com/szajbus/uploadpack

ダウンロードしたファイルを「upload_pack」にリネームして app→Pluginフォルダに入れる。

テーブル作成
[php]

— テーブルの構造 `images`

CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`img_file_name` varchar(255) NOT NULL,
`title` varchar(255) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=45 ;
[/php]

Configフォルダのbootstrap.phpにuploadpackを読み込むよ
bootstrap.phpに追記
[php]
CakePlugin::loadAll();
[/php]

Model
Image.php
[php]
class Image extends AppModel {

/**
* Validation rules
*
* @var array
*/
var $name = ‘Image’;
var $actsAs = array(
‘UploadPack.Upload’ => array(
‘img’ => array(
‘styles’ => array(
‘big’ => ‘200×200’,
‘small’ => ‘120×120’,
‘thumb’ => ’80×80′,
)
)
)
);
}

[/php]

イメージ画像が保存されるフォルダの指定がないときは、「webroot→upload→imagesに保存される。
てすので、webrootに”uploadフォルダ”とそのフォルダの中に”imagesフォルダ(勝手に生成されるみたい・・・モデル名だよ)”を作成する。

Controller
ImagesController.php
[php]
class ImagesController extends AppController {
var $uses = array(‘Image’);
var $helpers = array(‘Form’,’UploadPack.Upload’); //ヘルパー読み込み
function index(){
$this->set(‘images’, $this->Image->find(‘all’));
//debug($this->Image->find(‘all’));
}
function show($id) {
$this->set(‘images’, $this->Image->findById($id));
debug($this->Image->findById($id));
}
function add(){
if(!empty($this->data)){
if($this->Image->save($this->data)){
$this->redirect(‘/images’);
}
}
}
function edit($id = null){
$this->Image->id = $id;
if (empty($this->data)){
$this->data = $this->Image->read();
}else{
if ($this->Image->save($this->data[‘Image’])){
$this->redirect(‘/images’);
}
}
}
}
[/php]

View
add.ctp
※bootstrapを使用する場合はここ注意!BootstrapForm->create(‘Image’, array(‘class’ => ‘form-horizontal’,‘type’ => ‘file’));?>
[php]
<?php echo $this->Form->create(‘Image’, array(‘type’ => ‘file’)); ?>
<table>
<tr>
<th>TITLE</th><td><?php echo $this->Form->text(‘Image.title’); ?></td>
</tr>
<tr>
<th>IMAGE</th>
<td>
<?php echo $this->Form->file(‘Image.img’);?>
<?php echo $this->Form->error(‘Image.img’);?></td>
</tr>
<tr>
<th></th>
<td>
<?php echo $this->Form->end(‘新規登録’);?></td>
</tr>
</table>
[/php]
View
index.ctp
[php]
<h2><?php echo $this->Html->link("Add New Image", "/images/add/"); ?></h2>
<table>
<tr>
<th>ID</th><th>TITLE</th><th>IMAGE</th><th>CREATED</th><th>EDIT</th>
</tr>
<?php foreach($images as $image):?><tr>
<td><?php echo $image[‘Image’][‘id’];?></td>
<td><?php echo $image[‘Image’][‘title’];?></td>
<td><?php echo $image[‘Image’][‘img_file_name’];?></td>
<td><?php echo $this->Upload->uploadImage($image, ‘Image.img’, array(‘style’ => ‘thumb’)) ?></td> //モデルで設定した’thumb’を表示させる
<td><?php echo $image[‘Image’][‘created’];?></td>
<td><?php echo $this->Html->link("EDIT", "/edit/".$image[‘Image’][‘id’]); ?>
<?php echo $this->Html->link("show", "/images/show/".$image[‘Image’][‘id’]); ?></td>
</tr>
<?php endforeach;?>
</table>
[/php]

View
show.ctp
[php]
<td><?php echo $this->Upload->uploadImage($images, ‘Image.img’, array(‘style’ => ‘big’)) ?></td> //モデルで設定した’big’を表示させる
[/php]

Upload->uploadImage(… バージョンでヘルパー関数がuploadImageでした。

上手くいきました

備考

イメージが無い時の表示を変える
[php]
‘UploadPack.Upload’ => array(
‘img’ => array(
‘default_url’ => ‘/img/noimage.gif’,
)
)
);
[/php]

バリデーション ファイルサイズとアップロードの種類
[php]
public $validate = array(
‘img’ => array(
‘maxSize’ => array(
‘rule’ => array(‘attachmentMaxSize’, 5000000),
‘message’ => ‘5MB以下のファイルにしてください。’
),
‘attachmentContentType’ => array(
‘rule’ => array(‘attachmentContentType’, array(‘image/jpeg’)),
‘message’ => ‘アップロードできるのはjpegファイルのみです。’
),
)
);
[/php]
View
エラーメッセージの表示欄
[php]
echo $this->BootstrapForm->file(‘Report.img’);
echo ‘<span style="color:#B94A48;" class="help-inline error-message">’ . $this->BootstrapForm->error(‘Report.img’) . ‘</span>’;
[/php]

メール送信3(editでidを取ってる場合)

Contoller
[php]
App::uses(‘AppController’, ‘Controller’,’CakeEmail’, ‘Network/Email’);
public $components = array(‘Session’,’ContactMail’);
///////////////////////

public function contact($id = null) {
$this->Report->id = $id;
if (!$this->Report->exists()) {
throw new NotFoundException(__(‘Invalid %s’, __(‘report’)));
}
if ($this->request->is(‘post’) || $this->request->is(‘put’)) {
if ($this->Report->save($this->request->data)) {
$contact = $this->Report->findById($id); //保存後IDを取得

$this->ContactMail->send(
‘お問い合わせを送信しました’, //件名
‘contact’, //テンプレートファイル名
$contact, //渡すデータ
$contact[‘Child’][‘email’], //メールアドレス
$contact[‘Child’][‘childname’] . ‘様’ //名前
);

$this->Session->setFlash(
__(‘お問い合わせを送信しました’),
‘alert’,
array(
‘plugin’ => ‘TwitterBootstrap’,
‘class’ => ‘alert-success’
)
);
$this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(
__(‘送信内容にエラーがあります。エラーメッセージに従って内容を修正してください。’),
‘alert’,
array(
‘plugin’ => ‘TwitterBootstrap’,
‘class’ => ‘alert-error’
)
);
}
} else {
$this->request->data = $this->Report->read(null, $id);
}
$users = $this->Report->User->find(‘list’);
$children = $this->Report->Child->find(‘list’);
$this->set(compact(‘users’, ‘children’));
}
[/php]

/Component/ContactMailComponent.php
[php]
<?php
App::uses(‘CakeEmail’, ‘Network/Email’);
class ContactMailComponent extends Component {
// SMTP設定
public $from_mail = ‘xxxxxxx@xxxxxx.jp’;//送信元メールアドレス
public $from_name = null; //送信者名 nullでも可

public $config = array (
‘host’ => ‘smtp.xxxx.jp’, //送信サーバーを書くよ
‘port’ => 587, //
‘username’ => ‘xxxxxxxx@xxxxx.jp’, //メールアドレス書くよ
‘password’ => ‘xxxxxx’, //パスワード書くよ
‘transport’ => ‘Smtp’  
);

function send($subject, $template, $data, $to_mail, $to_name = null) {

// 送受信者設定
if( is_null($to_name) ) {
$to_name = $to_mail;
}
if( is_null($this->from_name) ) {
$this->from_name = $this->from_mail;
}

// 送信処理
$email = new CakeEmail($this->config);
$email
->template($template, ‘layout’)
->viewVars(array(‘data’ => $data))
->emailFormat(‘text’)
->to(array($to_mail => $to_name))
->from(array($this->from_mail => $this->from_name))
->bcc(array($this->from_mail => $this->from_name)) //->bcc(‘xxxx@xxxxx.jp’) BCCで他のメールアドレスにも送る
->subject($subject)
->send();
}
}
?>
[/php]

Cakephp をCPIサーバーで使う

webrootに.htaccessをおいたら動いた

[php]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

[/php]

appのある同じ階層に.htaccessをおいたら動いた
[php]
<IfModule mod_rewrite.c>
AddHandler x-httpd-php528 .php

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>
[/php]

入力時カレンダー bootstrap-datetimepicker 

http://tarruda.github.io/bootstrap-datetimepicker/

webroot/js/bootstrap-datetimepicker.min.js
webroot/js/bootstrap-datepicker.js
webroot/js/bootstrap-datepicker.ja.js //これはなぜだか効かないが入れておこ
webroot/css/bootstrap-datetimepicker.min.css

bootstrap.ctp
[php]
Html->css(‘bootstrap-datetimepicker.min’); ?>


Html->script(‘bootstrap-datetimepicker.min.js’, array( ‘inline’ => true )); ?>

[/php]

view
[php]

BootstrapForm->input(‘user_id’, array(‘label’ => ‘ユーザー名’)); ?>


BootstrapForm->input(‘daydata’, array(‘data-format’ => ‘yyyy-MM-dd’ ,’label’ => ‘第1回’,’type’ => ‘text’)); ?>




[/php]

ページネーション

http://hijiriworld.com/web/cakephp-%E3%83%9A%E3%83%BC%E3%82%B8%E3%83%8D%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%92%E6%94%BB%E7%95%A5%E3%81%99%E3%82%8B/

コンディションをいれて絞り込む
[php]
$conditions = array(‘part’ => 5);
$data = $this->paginate($conditions);
[/php]

又は’マイページ’
[php]
//ログインユーザーデータを取得して、ReportとbelongToでつながっているChildのユーザーIDと同じやつのReportデータだけ取得
$userinfo = $this->Auth->user(array(‘fields’ => ‘id’));
$conditions = array(‘Child.user_id’ => $userinfo);
$this->Report->recursive = 0;
//debug($this->Report->recursive = -2);
$this->set(‘reports’, $this->paginate($conditions));
[/php]

フォームの確認画面を自動生成 autoConfirm

autoConfirm.jsをダウンロード
http://blog.material-being.com/portfolio/auto_confirm/

[php]
<?php echo $this->Html->script(‘jquery-1.7.2.min’, array(‘inline’ => false)); ?>
<?php echo $this->Html->script(‘jquery.ba-hashchange.min’, array(‘inline’ => false)); ?>
<?php echo $this->Html->script(‘autoConfirm’, array(‘inline’ => false)); ?>
[/php]

[php]
//確認画面を表示させたい<form></form>のclassに"autoConfirm"を指定します。
echo $this->Form->create(‘xxxx’, array(‘action’ => ‘contact’, ‘type’ => ‘post’, ‘class’ => ‘autoConfirm’));

//Back(戻る)ボタンを配置する
echo $this->Form->button(‘戻る’, array(‘type’ => ‘button’, ‘class’ => ‘autoConfirmBack’));

[/php]

autoConfirm.jsの設定を変更する
autoConfirm.js
[php]
var confirmName = ‘確認’; //入力画面におけるSubmitボタンの値
var submitName = ‘送信’; //確認画面におけるSubmitボタンの値
var speed = 300; //アニメーションの速度(ミリ秒)
var convertLf = true; //プレビュー時、テキストエリアの改行をbrタグに置き換える
[/php]

メール送信2

http://weble.org/2012/05/11/cakephp-getlastinsertid
[php]
CREATE TABLE IF NOT EXISTS `contacts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`from` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`body` text COLLATE utf8_unicode_ci NOT NULL,
`created` int(11) NOT NULL,
`modified` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
[/php]

/app/config/email.php.default を email.php にリネーム

ContactsController.php
[php]
App::uses(‘AppController’, ‘Controller’,’CakeEmail’, ‘Network/Email’);

public $components = array(‘ContactMail’);

public function contact() {
if ($this->request->is(‘post’)) {
$this->Contact->create();
if ($this->Contact->save($this->request->data)) {
$id = $this->Contact->getLastInsertID(); //保存後IDを取得
$contact = $this->Contact->findById($id); //保存後IDを取得

$this->ContactMail->send(
‘お問い合わせを送信しました’, //件名
‘contact’, //テンプレートファイル名
$contact, //渡すデータ
$contact[‘Contact’][‘from’], //メールアドレス
$contact[‘Contact’][‘name’] . ‘様’ //名前
);

$this->Session->setFlash(__(‘お問い合わせを送信しました’));
$this->redirect(array(‘action’ => ‘index’));

} else {
$this->Session->setFlash(__(‘送信内容にエラーがあります。エラーメッセージに従って内容を修正してください。’));
}
}
//$this->set(‘title_for_layout’, ‘お問い合わせ’);
debug();

}
[/php]

app/Controller/Component/ContactMailComponent.php を作成
[php]
<?php
App::uses(‘CakeEmail’, ‘Network/Email’);
class ContactMailComponent extends Component {

// SMTP設定
public $from_mail = ‘xxxxxxx@gmail.com’; //送信元メールアドレス
public $from_name = null; //送信者名 nullでも可
public $config = array (
‘host’ => ‘ssl://smtp.gmail.com’,
‘port’ => 465,
‘username’ => ‘xxxxxxx@gmail.com’,
‘password’ => ‘xxxxxxx’,
‘transport’ => ‘Smtp’
);

function send($subject, $template, $data, $to_mail, $to_name = null) {

// 送受信者設定
if( is_null($to_name) ) {
$to_name = $to_mail;
}
if( is_null($this->from_name) ) {
$this->from_name = $this->from_mail;
}

// 送信処理
$email = new CakeEmail($this->config);
$email
->template($template, ‘layout’)
->viewVars(array(‘data’ => $data))
->emailFormat(‘text’)
->to(array($to_mail => $to_name))
->from(array($this->from_mail => $this->from_name))
->bcc(array($this->from_mail => $this->from_name))
->subject($subject)
->send();
}
}
?>
[/php]

app/View/Layouts/Emails/text/layout.ctp を作成
[php]
<?php echo $content_for_layout;?>
/////////////////////////////////////
よろよろ
[/php]

app/View/Emails/text/contact.ctp
[php]
<?php echo $data[‘Contact’][‘name’]; ?>様

お問い合わせいただき、ありがとうございますた

/////////////////////////////////////
お問い合わせ内容
/////////////////////////////////////

――――――――――――――――――――――
件名:<?php echo $data[‘Contact’][‘subject’]; ?>

――――――――――――――――――――――
<?php echo $data[‘Contact’][‘body’]; ?>

――――――――――――――――――――――
[/php]

app/View/Contacts/contact.ctp
[php]

<?php
echo $this->Form->create(‘Contact’, array(‘action’ => ‘contact’, ‘class’ => ‘autoConfirm’));
echo $this->Form->input(‘Contact.subject’, array(‘label’ => ‘タイトル’));
echo $this->Form->input(‘Contact.name’, array(‘label’ => ‘お名前’));
echo $this->Form->input(‘Contact.from’, array(‘label’ => ‘メールアドレス’));
echo $this->Form->input(‘Contact.body’, array(‘label’ => ‘本文’));
echo $this->Form->button(‘戻る’, array(‘type’ => ‘button’, ‘class’ => ‘autoConfirmBack’));
echo $this->Form->submit(‘送信’, array(‘div’ => false));
echo $this->Form->end();
?>
[/php]

find で習得したデータをviewに表示

コントローラー

[php]
$users = $this->Child->User->find(‘list’,array(
‘fields’=>array(‘username’), ////取りたいフィールド名の配列
));
$this->set(compact(‘users’));
[/php]

add or edit

[php]
echo $this->BootstrapForm->input(‘user_id’, array(‘label’ => ‘ユーザー名’,’options’=>$users)); //optionsで指定する
[/php]

パスワードを暗号化させない

http://www.maruhisa.org/2011/11/30/cakephp2-0using_plainpassword/
http://www.matomater.com/687/

[php]
/lib/Cake/Utility/Security.php 107行目あたり

public static function hash($string, $type = null, $salt = false) {

return $string;
/*if (empty($type)) {
$type = self::$hashType;
}
$type = strtolower($type);

if ($type === ‘blowfish’) {
return self::_crypt($string, $salt);
}
if ($salt) {
if (!is_string($salt)) {
$salt = Configure::read(‘Security.salt’);
}
$string = $salt . $string;
}

if (!$type || $type === ‘sha1’) {
if (function_exists(‘sha1’)) {
return sha1($string);
}
$type = ‘sha256’;
}

if ($type === ‘sha256’ && function_exists(‘mhash’)) {
return bin2hex(mhash(MHASH_SHA256, $string));
}

if (function_exists(‘hash’)) {
return hash($type, $string);
}
return md5($string);*/
}
[/php]

cakephpで javascriptの使い方

[php]
<p><a href="javascript:void(0)" onclick="show_block();">表示切替</a></p>
<div id="hoge" style="display:none;">こっち見んな!</div>

<?php
$this->Html->scriptStart(array(‘inline’=>false));
?>
function show_block(){
if(document.getElementById("hoge").style.display == ""){
document.getElementById("hoge").style.display = "none";
}else{
document.getElementById("hoge").style.display = "";
}
}
<?php
$this->Html->scriptEnd();
?>
[/php]