2014-06-10 4 views
0

다음과 비슷한 테이블 내에 폼이 있습니다.이 폼을 제출하면 입력에 따라 여러 개의 새 리소스를 만들어야하는 Modx 스 니펫이 있습니다. 배열이 통과합니다.폼에서 여러 개의 Modx 리소스를 만들려고 시도합니다.

<table class="table responsive-table"> 
      <thead> 

       <th>pagetitle</th> 
       <th>longtitle</th> 
      </thead> 
      <tbody> 
       <tr> 

       <td><input type="text" name="pagetitle[]" value="" /></td> 
       <td><input type="text" name="longtitle[]" value=""/></td>  
       </tr> 
       <tr> 
       <td><input type="text" name="pagetitle[]" value="" /></td> 
       <td><input type="text" name="longtitle[]" value=""/></td>  
       </tr> 
      </tbody> 

     </table> 

아래 사항이 실행될 때 어떤 일이 발생하는지는 예상대로 새 리소스를 생성하지만 모든 필드는 "어레이"로 설정됩니다. 배열의 값이 아닙니다. $allFormFields

<?php 
$allFormFields = $hook->getValues(); 


foreach ($allFormFields as $key => $value) 
{ 
    $doc = $modx->newObject('modResource'); 
    $doc->set('createdby', $modx->user->get('id')); 
    $doc->set('pagetitle', $value['pagetitle']); 
    $doc->set('longtitle', $value['longtitle']); 
    $doc->save(); 
} 

return true; 

답변

1

print_r()은 매우 가능성이 당신이 뭔가를 줄 것이다 :

당신이 $allFormFields['pagetitle']에 자원 필드를 설정하려고 할 때 '배열'을 얻고있는 이유
// dump of form values 
Array (
    [pagetitle] => Array (
     [0] => 'pagetitle1' 
     [1] => 'pagetitle2' 
    ), 
    [longtitle] => Array (
     [0] => 'longtitle1' 
     [1] => 'longtitle2' 
    ), 
) 

.

난 당신이 무슨 일을하는지 완전히 잘 모르겠지만, 아마이 대신 같은 양식을 구성하는 것이 좋습니다 것 : 그런 다음

<input type="text" name="resource[0][pagetitle]" value="" /> 
<input type="text" name="resource[0][longtitle]" value="" />  

<input type="text" name="resource[1][pagetitle]" value="" /> 
<input type="text" name="resource[1][longtitle]" value="" /> 

할 수 있습니다 이와 같은 각 자원에 대한 양식 필드를 통해 루프 :

<?php 
$allFormFields = $hook->getValues(); 
$userId = $modx->user->get('id'); 

foreach ($allFormFields['resource'] as $fields) { 
    $doc = $modx->newObject('modResource'); 
    $doc->set('createdby', $userId); 
    $doc->set('pagetitle', $fields['pagetitle']); 
    $doc->set('longtitle', $fields['longtitle']); 
    $doc->save(); 
} 
+0

개체의 fromArray 메서드는 여러 개의 set 메서드 대신 유용 할 것이라고 생각합니다. – proxyfabio

0

덕분에

은 내가 기대했다으로는 그 이하 작동하고 결국, okyanet :

<?php 
$allFormFields = $hook->getValues(); 

$resources = array(); 

foreach ($allFormFields as $field => $values) { 
    if (is_array($values)) { 
     foreach ($values as $key => $value) { 
      $resources[$key][$field] = $value; 
     } 
    } 
} 



foreach ($resources as $resource) { 

    if ($resource[pagetitle] == '') { 
     continue; 
    } 
    $doc = $modx->newObject('modResource'); 
    $doc->fromArray($resource); 
    $doc->set('createdby', $modx->user->get('id')); 
    $doc->set('template', $hook->getValue('template')); 
    $doc->set('parent', $hook->getValue('parent')); 
    $doc->save(); 
} 
return true;