LoginSignup
0
0

More than 5 years have passed since last update.

入力値が2つ以上あるときの、MyWidget::updateの書き方

Posted at

はじめに

Wordpressにウィジェットというのがありまして、元から用意されているのとか、プラグイン付属でついてくるやつとかあります。
さらにその他に、自分でウィジェット作って、functions.phpから登録することもできます。

そのやりかたはこちらにバッチリまとまっています。
http://liginc.co.jp/web/wp/112370

これを参考にしていったときに、ウィジェット更新処理のところで引っかかりました。

更新処理

ウィジェット設定画面は、外観→カスタマイズ(から、ウィジェットボタンを押す)の画面にあります。例えばデフォルトのRSSウィジェットだと、こんな感じです。
de182ce293347ee1a2f843a2a69e9caa.png

ここでテキストボックスに入力とかしたときにupdateメソッドが走る。1個フォーカス離したタイミングとかで1個ずつバリデーションされて、登録されます。
バリデーションに引っかかると、登録されない。

先ほどの記事に書かれている更新処理のupdateメソッドがこんな感じです。

MyWidget.php
    /** 新しい設定データが適切なデータかどうかをチェックする。
     * 必ず$instanceを返す。さもなければ設定データは保存(更新)されない。
     *
     * @param array $new_instance  form()から入力された新しい設定データ
     * @param array $old_instance  前回の設定データ
     * @return array               保存(更新)する設定データ。falseを返すと更新しない。
     */
    function update($new_instance, $old_instance) {
        if(!filter_var($new_instance['email'],FILTER_VALIDATE_EMAIL)){
            return false;
        }
        return $new_instance;
    }

入力値が1個の時はこれでいいんですが。入力値が複数の時にうまく動かない。
ifのとこには成功判定を書くようにしました。

MyWidget.php
    function update($new_instance, $old_instance) {
        if ( !empty($new_instance['text']) ){
            $new_instance['count'] = $old_instance['count'];
            return $new_instance;
        }
        if ($new_instance['count'] > 0 
            && $new_instance['count'] < 10
            && is_numeric($new_instance['count'])
            ){
            $new_instance['text'] = $old_instance['text'];
            return $new_instance;
        }
        return false;
    }

if(テキスト1の成功判定){
// $new_instanceにテキスト2のデータを入れる
return $new_instance;
}
if(テキスト2の成功判定){
// $new_instanceにテキスト1のデータを入れる
return $new_instance;
}
return false;

という感じです。

なので、記事の書き方を生かすとこんな感じか。

MyWidget.php
    function update($new_instance, $old_instance) {
        if(!filter_var($new_instance['email'],FILTER_VALIDATE_EMAIL)){
            return false;
        } else {
            $new_instanct['text'] = $old_instance['text'];
        }
        return $new_instance;
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0