---
name: perfex-forms
description: Gestao de formularios em modulos Perfex CRM -- form_open(), tokens CSRF, validacao e AJAX. Baseado apenas na documentacao oficial.
---

# /perfex-forms - Formularios Perfex CRM

Gestao de formularios em modulos. **Zero assumptions, zero hallucinations** - apenas documentacao oficial.

---

## Documentacao Base

- [Working With Forms](https://help.perfexcrm.com/working-with-forms/)
- [CodeIgniter Form Helper](https://codeigniter.com/userguide3/helpers/form_helper.html)

---

## Regra Fundamental: form_open()

**SEMPRE usar `form_open()` para gerar token CSRF automaticamente.**

```php
<?php echo form_open(admin_url('meu_modulo/save')); ?>
    <!-- Inputs aqui -->
<?php echo form_close(); ?>
```

**NUNCA usar `<form>` HTML directo** - sem CSRF protection.

---

## Sintaxe form_open()

```php
// Basico
echo form_open(admin_url('meu_modulo/save'));

// Com atributos
echo form_open(admin_url('meu_modulo/save'), [
    'id'    => 'form-meu-modulo',
    'class' => 'form-horizontal',
]);

// Com upload de ficheiros
echo form_open_multipart(admin_url('meu_modulo/upload'), [
    'id' => 'form-upload',
]);

// Fechar formulario
echo form_close();
```

---

## Elementos de Formulario

Todos os elementos com exemplos completos em: `references/elementos-formulario.md`

Elementos disponiveis: Input Text, Textarea, Select, Select AJAX, Checkbox, Radio, Date Picker, DateTime Picker, File Upload, Hidden.

**Padrao geral:**
```php
<div class="form-group">
    <label for="CAMPO" class="control-label">
        <?php echo _l('CAMPO'); ?>
        <span class="text-danger">*</span>  <!-- se obrigatorio -->
    </label>
    <input type="text" id="CAMPO" name="CAMPO" class="form-control"
           value="<?php echo isset($item) ? html_escape($item->CAMPO) : ''; ?>">
</div>
```

---

## Validacao Client-Side

O Perfex usa jQuery Validation. Usar `appValidateForm()`:

```php
<?php init_tail(); ?>
<script>
$(function(){
    appValidateForm($('#form-meu-modulo'), {
        name: {
            required: true,
            minlength: 3
        },
        email: {
            required: true,
            email: true
        },
        amount: {
            required: true,
            number: true,
            min: 0
        }
    });
});
</script>
</body>
</html>
```

### Regras de Validacao

| Regra | Descricao |
|-------|-----------|
| `required: true` | Campo obrigatorio |
| `email: true` | Email valido |
| `number: true` | Numero |
| `digits: true` | Apenas digitos |
| `minlength: N` | Minimo N caracteres |
| `maxlength: N` | Maximo N caracteres |
| `min: N` | Valor minimo |
| `max: N` | Valor maximo |
| `equalTo: '#field'` | Igual a outro campo |

---

## Validacao Server-Side

```php
public function save()
{
    if (!$this->input->post()) {
        redirect(admin_url('meu_modulo'));
    }

    $this->load->library('form_validation');

    $this->form_validation->set_rules('name', _l('name'), 'required|min_length[3]');
    $this->form_validation->set_rules('email', _l('email'), 'required|valid_email');
    $this->form_validation->set_rules('amount', _l('amount'), 'required|numeric');

    if ($this->form_validation->run() === false) {
        set_alert('danger', validation_errors());
        redirect(admin_url('meu_modulo/create'));
    }

    $data = [
        'name'   => $this->input->post('name'),
        'email'  => $this->input->post('email'),
        'amount' => $this->input->post('amount'),
    ];

    // ... guardar
}
```

---

## AJAX com jQuery

### POST Simples

```javascript
$.post(admin_url + 'meu_modulo/ajax_save', {
    name: $('#name').val(),
    description: $('#description').val()
}).done(function(response) {
    response = JSON.parse(response);
    if (response.success) {
        alert_float('success', response.message);
    } else {
        alert_float('danger', response.message);
    }
});
```

### Controller AJAX

```php
public function ajax_save()
{
    if (!$this->input->is_ajax_request()) {
        show_404();
    }

    if (!staff_can('create', 'meu_modulo')) {
        echo json_encode(['success' => false, 'message' => _l('access_denied')]);
        return;
    }

    $data = [
        'name'        => $this->input->post('name'),
        'description' => $this->input->post('description'),
    ];

    $id = $this->meu_modulo_model->add($data);

    echo json_encode([
        'success' => (bool) $id,
        'id'      => $id,
        'message' => $id ? _l('added_successfully') : _l('error_occurred'),
    ]);
}
```

---

## Excluir CSRF para Webhooks

Para endpoints que recebem callbacks externos:

```php
// modules/meu_modulo/config/csrf_exclude_uris.php
<?php
defined('BASEPATH') or exit('No direct script access allowed');

return [
    'meu_modulo/webhook',
    'meu_modulo/callback',
    'meu_modulo/api/.*',  // Regex
];
```

---

## Anti-Patterns (NUNCA FAZER)

| Anti-Pattern | Risco | Alternativa |
|--------------|-------|-------------|
| `<form>` HTML directo | CSRF bypass | `form_open()` |
| Valores sem `html_escape()` | XSS | Escape sempre |
| Validacao so client-side | Bypass | Validar server tambem |
| AJAX sem verificar `is_ajax_request()` | Acesso directo | Verificar sempre |

---

## Checklist Formularios

```
1. [ ] form_open() para todos os formularios
2. [ ] html_escape() em todos os values
3. [ ] Validacao client-side (appValidateForm)
4. [ ] Validacao server-side (form_validation)
5. [ ] Permissoes verificadas no controller
6. [ ] CSRF excluido apenas para webhooks
7. [ ] form_open_multipart() para uploads
8. [ ] is_ajax_request() em endpoints AJAX
```

---

## References

- `references/elementos-formulario.md` - Todos os elementos HTML/PHP com exemplos
- `references/formulario-completo-exemplo.md` - View completa com todos os elementos

---

**Fonte:** help.perfexcrm.com/working-with-forms

---

## Healing Log

Registo de erros conhecidos e como evitá-los. Lido automaticamente antes de executar.

```jsonl
{"date":"","issue":"","fix":"","source":"user|auto"}
```

*Adicionar nova linha após cada erro corrigido.*
