How can I return a value from a CakePHP list array for use in a form?

I use CakePHP to develop an application, and I have some basic permissions that are designed to limit user capabilities and help prevent errors.

I have a form where someone with a specific permission or higher can create a new employee. One of the fields on the form allows them to associate the school with the staff. If they have minimal access, I would like the selection to be automatically filled, since the school with which the creator was created, and then, if they are an administrator, they have the opportunity to choose from a choice.

In the controller, I call this line, which fills the array of schools:

$this->set('schools', $this->Staff->School->find('list', array('conditions' => array('School.active' => !null), 'order' => array('name' => 'ASC'))));

And the array looks like this:

array(4) {
  [2]=> string(15) "School A"
  [3]=> string(15) "School B"
  [1]=> string(17) "School C"
  [6]=> string(21) "School D"
}

AuthComponent : AuthComponent::user('school_id') 1.

:

if (AuthComponent::user('admin') == 1) {
    echo $this->Form->input('school_id', array('label' => 'School *',    'options' => array($schools), 'required' => 'required'));
} else {
    echo $this->Form->input('school_id', array('label' => 'School *', 'value' => $schools[AuthComponent::user('school_id')], 'disabled' => 'disabled'));
}

- . var_dump($schools[AuthComponent::user('school_id')];, String(8) => "School C", , .

- ?

+4
1

:

'conditions' => array('School.active' => !null)

!null true, :

'conditions' => array('School.active' => true)

not-null, :

'conditions' => array('School.active NOT' => null)

'conditions' => array('NOT' => ('School.active' => null))

'options' => array($schools)

$schools - , select optGroup "0". :

<select name="data[User][school_id]" id="UserSchoolId">
    <optgroup label="0">
        <option value="2">School A</option>
        <option value="3">School B</option>
        <option value="1">School C</option>
        <option value="6">School D</option>
    </optgroup>
</select>

, , , . , , html, , .

, CakePHP schools_id select, schools. , , :

echo $this->Form->input(
    'school_id',
    array(
        'label' => 'School *',
        'options' => $schools, // implicit
        'value' => $schools[AuthComponent::user('school_id')],
        'disabled' => 'disabled'
    )
);

:

<select name="data[User][school_id]" value="School C" id="UserSchoolId">
    <option value="2">School A</option>
    <option value="3">School B</option>
    <option value="1">School C</option>
    <option value="6">School D</option>
</select>

- html , , .

, :

$options = ['label' => 'School *'];
if (!AuthComponent::user('admin')) {
    $options += [
        'value' => AuthComponent::user('school_id'),
        'disabled' => 'disabled'
    ];
}
echo $this->Form->input('school_id', $options);

, - html, . ( ), , school_id ( ) auth'ed / .

+4

Source: https://habr.com/ru/post/1608638/


All Articles