2011-11-14 4 views
0

私はDrupalフォルダにたくさんの配列を作成したいと思います。しかし、私はこれを行う方法がわかりません。基本的には、常に同じ構造です。配列で配列を作る

$form['actions']['saveasdraft']['#type'] = 'submit'; 
$form['actions']['saveasdraft']['#access'] = true; 
$form['actions']['saveasdraft']['#value'] = 'Save as Draft'; 
$form['actions']['saveasdraft']['#weight'] = 11; 
$form['actions']['saveasdraft']['#submit'][0] = 'node_fiche_form_submit'; 

$form['actions']['saveascurrent']['#type'] = 'submit'; 
$form['actions']['saveascurrent']['#access'] = true; 
$form['actions']['saveascurrent']['#value'] = 'Save as New version'; 
$form['actions']['saveascurrent']['#weight'] = 12; 
$form['actions']['saveascurrent']['#submit'][0] = 'node_fiche_form_submit'; 

... 

これは簡単な方法ですか?

答えて

2

それを行うには「正しい」方法は、(Drupal coding standardsを参照)、このようなものです:

Drupalのコアモジュールは、それを行う方法(と私が今まで見てきたすべての貢献のモジュールが)だ
$form['action']['saveasdraft'] = array(
    '#type' => 'submit', 
    '#access' => TRUE, 
    '#value' => 'Save as Draft', 
    // etc... 
); 

$form['action']['saveascurrent'] = array(
    '#type' => 'submit', 
    '#access' => TRUE, 
    '#value' => 'Save as New version', 
    // etc... 
); 

EDITあなたはあなたが行うことができるようになるだろう最高のは、いくつかのデフォルト値を設定されているコードを繰り返す心配している場合は

...保存する必要があり、数百行:)

$defaults = array('#type' => 'submit', '#access' => TRUE, /* etc... */); 

$form['action']['saveasdraft'] = $defaults + array(
    '#value' => 'Save as Draft' 
); 

$form['action']['saveascurrent'] = $defaults + array(
    '#value' => 'Save as New version' 
); 

希望すること

+0

正解!忘れてた。しかし、可能な限り少ないコードで100以上の配列を追加する方法はありますか? – Michiel

+0

私はそれが助けてくれることを願って更新しました:) – Clive

+0

はい、それは役に立ちます:-)多くありがとう!私は一度それ以上投票することができます;-) – Michiel

1

DRY(自分を繰り返さないでください)のルールを採用してください。あなたはそれを行うことができます。適切な要素を返す関数を作成することによって、そのように大きな配列に入力される。

function form_element($value, $weight, $type = 'submit', $access = true, 
    $submit = 'node_fiche_form_submit') { 
    return array(
     '#type' => $type, 
     '#access' => $access, 
     '#value' => $value, 
     '#weight' => $weight, 
     '#submit' => array($submit), 
    ); 
}; 

、あなたがそのようにそれを使用することができます:

$form['actions']['saveasdraft'] = form_element('Save as Draft', 11); 
$form['actions']['saveascurrent'] = form_element('Save as New version', 12); 
// ...and so on 

を証明するためにthis codepadを参照してください。

PS。もちろん、ヘルパー関数の意味がわかりにくく、矛盾しない名前をいくつか作り出すべきですが、アプローチは最短のものです。

+0

すばらしいヒント!ありがとう! '' #submit '=> array($ submit) 'はなぜ配列ですか? – Michiel

+1

@Michiel: '#submit'キーは常に配列として渡されます。実際には、要素の最後に '[0]'で示される元のコードでそのまま渡します: '$ form ['actions'] ['saveascurrent'] ['#submit'] [0]' – Clive

+0

あなたが '$ form ['actions'] ['saveascurrent'] ['#submit'] [0] = 'node_fiche_form_submit';と' [0] 'は一般的にそれを意味するので、Cliveは正しいです$ form ['actions'] ['saveascurrent'] ['#submit'] 'は少なくとも一つの要素を持つ配列です。 – Tadeck