How do I approach this data writer?

TheBigK

Well-known member
I need help in making this data writer work. Here's what I have.

PHP:
$department_name = $this->_input->filterSingle('department_name', XenForo_Input::STRING, array('array' => true));
$department_email = $this->_input->filterSingle('department_email', XenForo_Input::STRING, array('array' => true));
$dw = XenForo_DataWriter::create('ContactUs_DataWriter_Contact');

//The following approach, I think is wrong. 
for ($i = 0; $i <= sizeof($department_name); $i++)
{
$dw->set('department_name', $department_name[$i]);
$dw->set('department_email', $department_email[$i]);
$dw->save();
}
The idea is to set both $department_name and corresponding $department_email at a time. I'm however constantly getting the following error -

Undefined offset: 1
  1. XenForo_Application::handlePhpError() in ContactUs/ControllerAdmin/Index.php at line 34
  2. ContactUs_ControllerAdmin_Index->actionAdd() in XenForo/FrontController.php at line 347
  3. XenForo_FrontController->dispatch() in XenForo/FrontController.php at line 134
  4. XenForo_FrontController->run() in /Users/CE-Mac-Two/Sites/xf/admin.php at line 13
 
PHP:
$department_name = $this->_input->filterSingle('department_name', XenForo_Input::ARRAY_SIMPLE);
$department_email = $this->_input->filterSingle('department_email', XenForo_Input::ARRAY_SIMPLE);

foreach($department_name as $key => $name) {
    $dw = XenForo_DataWriter::create('ContactUs_DataWriter_Contact');
    $dw->bulkSet(array(
        'department_name' => $name,
        'department_email' => $department_email[$key]
    ));
    $dw->save();
}

Or you might merge those two arrays together first.
 
@TheBigK your approach wasn't entirely wrong since the index of the inputs are numerical. The for loop you used, changing '<=' to '<' in the condition will fix the error you are getting...
But yes! Merging the arrays first is the way to go. :D

EDIT:
The reason for change is that for an array with 'sizeof' 6, the last index is 5 (n - 1, since index starts from 0)
 
@TheBigK your approach wasn't entirely wrong since the index of the inputs are numerical. The for loop you used, changing '<=' to '<' in the condition will fix the error you are getting...
But yes! Merging the arrays first is the way to go. :D

EDIT:
The reason for change is that for an array with 'sizeof' 6, the last index is 5 (n - 1, since index starts from 0)
Thanks. I haven't seen anyone using a for loop; so I wasn't very sure. Why is merging the arrays a recommended approach?
 
Top Bottom