Select and option attribute disabled

I have this query

$motorcycles = $this->Reservations->Motorcycles->find('list', keyField: 'id', valueField: 'label');

Motorcycles has column active = 0/1
If active = 0 i can to this option add atribute disabled. How to make? Is it possible to get a field directly into the form that will contain the disabled attribute?

This form:

echo $this->Form->control('motorcycle_id', [
    'options' => $motorcycles,
]);

Thank you

Hi @shadowx.jb,

<?php
$motorcycles = [
    4 => "Honda",
    9 => "Suzuki",
    11 => "Yamaha",
    5 => "Kawasaki"
];
// id's of options you want the disabled attribute on
$disabled = [4, 11];
?>

<?php echo $this->Form->control('motorcycle_id', [
    'options' => $motorcycles,
    'disabled' => $disabled
]);

2024-04-03 15_26_47-CakePHP_ the rapid development php framework_ Temp

As to how you can build a list of ‘disabled’ ids for the control. Here is one idea:

 $disabled = $table->find()
            ->where(['active' => false])
            ->all()
            ->reduce(function ($accum, $current) {
                $accum[] = $current->id;
                return $accum;
            }, []);
1 Like

Thank you very much, can it be done in one query? So that the sheet contains items that are disabled?

Not sure I understand what you mean. But one query:

 $findResult = $table->find();

        $motorcycles = $findResult->all()
            ->combine('id', 'label');

        $disabled = $findResult->all()
            ->filter(function ($item) {
                return !$item->active;
            })
            ->reduce(function ($accum, $current) {
                $accum[] = $current->id;
                return $accum;
            }, []);

        $this->set(compact('motorcycles', 'disabled'));


1 Like

I mean one query, which then returns e.g.

        $motorcycles = [
            0 => [
                'value' => 1,
                'text' => 'Model X',
                'disabled' => false,
            ],
            1 => [
                'value' => 2,
                'text' => 'Model Y',
                'disabled' => true,
            ],
        ];

And the form can handle it, but I don’t know if it’s possible… then there’s no other solution than the one you wrote.

It is possible… some options:

  • Extending the FormHelper class and implementing your own logic.
  • Custom widget Form - 5.x.
1 Like

Thank you, i understand👍